Just An Application

June 18, 2013

Programming With Rust — Part Twelve: Even More Things We Need To Know – Methods

1.0 Implementations

Methods are defined for a specific type using an implementation.

For example, given this struct definition

    struct QName
    {
        prefix:    ~str,
        nsURI:     ~str,
        localPart: ~str
    }

we would do this to define methods on the type QName

    impl QName
    {
        ... method definitions go here ...
    }

2.0 Method Definitions

A method is defined in the same way as a function but with self or some kind of pointer to self as a special first parameter.

At runtime self is bound to the value on which the method has been invoked.

For example,

    impl QName
    {
        ...
        
        fn getPrefix(&self) -> ~str
        {
            self.prefix.clone()
        }

        ...
    }

Using a borrowed pointer to self means that the method is applicable to a value of type QName regardless of where it is stored.

If a method can modify the value on which it is called the self parameter must be declared mutable.

    impl QName
    {
        ...
        
        fn setPrefix(&mut self, prefix: ~str)
        {
            self.prefix = prefix;
        }
        
        ...
    }

3.0 Static Method Definitions

A static method definition is an ordinary function definition, or, if you prefer, a method definition without a self parameter.

We can define a static method new to create a QName value like this

    impl QName
    {
        ...
        
        
        fn new(prefix: ~str, nsURI: ~str, localPart: ~str) -> QName
        {
            QName { prefix: prefix, nsURI: nsURI, localPart: localPart }
        }
        
        ...
    }

4.0 Invoking Static Methods

Static methods are invoked as functions but with the name prefixed by the type name like so

    let rights = QName::new(~"dc", ~"http://purl.org/dc/elements/1.1/", ~"rights");


Copyright (c) 2013 By Simon Lewis. All Rights Reserved.

Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and owner Simon Lewis is strictly prohibited.

Excerpts and links may be used, provided that full and clear credit is given to Simon Lewis and justanapplication.wordpress.com with appropriate and
specific direction to the original content.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: