> For the complete documentation index, see [llms.txt](https://zenofchain.gitbook.io/sway-bian-cheng-yu-yan-geng-xin-zhong-the-sway-programming-languageupdatin/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zenofchain.gitbook.io/sway-bian-cheng-yu-yan-geng-xin-zhong-the-sway-programming-languageupdatin/4.-sway-yu-yan-ji-chu-sway-language-basics/4.7-fang-fa-he-guan-lian-han-shu-methods-and-associated-functions.md).

# 4.7 方法和关联函数 (Methods and Associated Functions)

Methods are similar to functions in that we declare them with the `fn` keyword and they have parameters and return a value. However, unlike functions, *Methods* are defined within the context of a struct (or enum), and either refers to that type or mutates it. The first parameter of a method is always `self`, which represents the instance of the struct the method is being called on.

方法与函数类似，我们用 `fn` 关键字声明它们，它们有参数并返回一个值。然而，与函数不同的是，*方法* 是在一个结构（或穷举）的上下文中定义的，并且可以引用该类型或对其进行变化。方法的第一个参数总是 `self`，它代表方法被调用的结构实例。

*Associated functions* are very similar to *methods*, in that they are also defined in the context of a struct or enum, but they do not actually use any of the data in the struct and as a result do not take *self* as a parameter. Associated functions could be standalone functions, but they are included in a specific type for organizational or semantic reasons.

*关联函数* 与 *方法* 非常相似，因为它们也是在解构或穷举的上下文中定义的，但它们实际上并不使用解构中的任何数据，因此不把 *self* 作为参数。关联函数可以是独立的函数，但出于组织或语义的原因，它们被包含在特定的类型中。

To declare methods and associated functions for a struct or enum, use an *impl block*. Here, `impl` stands for implementation.

要为一个结构或穷举，声明方法和关联函数，请使用 *impl块*。这里，`impl`代表实现。

```
script;

struct Foo {
    bar: u64,
    baz: bool,
}

impl Foo {
    // this is a _method_, as it takes `self` as a parameter.
    fn is_baz_true(self) -> bool {
        self.baz
    }

    // this is an _associated function_, since it does not take `self` as a parameter.
    fn new_foo(number: u64, boolean: bool) -> Foo {
        Foo {
            bar: number,
            baz: boolean,
        }
    }
}

fn main() {
    let foo = Foo::new_foo(42, true);
    assert(foo.is_baz_true());
}

```

To call a method, simply use dot syntax: `foo.iz_baz_true()`.

要调用一个方法，只需使用点语法： `foo.iz_baz_true()`。

Similarly to [free functions](https://fuellabs.github.io/sway/v0.38.0/book/basics/functions.html), methods and associated functions may accept `ref mut` parameters. For example:

与[自由函数](https://fuellabs.github.io/sway/v0.38.0/book/basics/functions.html)类似，方法和相关函数可以接受`ref mut`参数。例如：

```
struct Coordinates {
    x: u64,
    y: u64,
}

impl Coordinates {
    fn move_right(ref mut self, distance: u64) {
        self.x += distance;
    }
}

```

and when called:

以及当调用时：

```
    let mut point = Coordinates { x: 1, y: 1 };
    point.move_right(5);
    assert(point.x == 6);
    assert(point.y == 1);

```
