Localized V2 rewrite for this language is in progress. Showing English-first content for now.

函数

定义函数、返回值,以及效果注解。

函数

在 Sounio 中,函数是表达式: 代码块中的最后一个表达式会作为返回值。

基本函数

fn add(a: i32, b: i32) -> i32 {
    a + b
}

fn greet(name: string) {
    print("Hello, ")
    println(name)
}

调用函数

let sum = add(3, 5)  // 8
greet("World")       // Hello, World!

声明效果

规范要求副作用必须通过函数签名里的 with ... 声明。

fn log(msg: string) with IO {
    println(msg)
}

可以组合多个效果:

fn safe_div(a: i32, b: i32) -> i32 with Panic {
    if b == 0 {
        panic("division by zero")
    }
    a / b
}

方法(impl

可以在类型上定义函数:

struct Point {
    x: f64,
    y: f64,
}

impl Point {
    fn new(x: f64, y: f64) -> Point {
        Point { x: x, y: y }
    }

    fn distance(&self, other: &Point) -> f64 {
        let dx = self.x - other.x
        let dy = self.y - other.y
        sqrt(dx * dx + dy * dy)
    }
}

规范说明: 泛型、闭包与高阶函数是设计目标的一部分,但某些组合在编译器中仍可能在演进。

下一步