Cơ BảnGolang iconGolang

Hàm (function) trong Go khai báo thế nào?

Khai báo hàm cơ bản dùng từ khóa func.

Go hỗ trợ multiple return values và named returns.

go
// Hàm cơ bản
func add(a int, b int) int {
    return a + b
}

// Multiple return values
func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, fmt.Errorf("division by zero")
    }
    return a / b, nil
}

// Named return values
func swap(a, b int) (x, y int) {
    x, y = b, a
    return
}

// Functions là first-class citizens
add := func(a, b int) int { return a + b }

Functions là first-class citizens, có thể gán cho biến hoặc truyền như tham số.

Xem toàn bộ Golang cùng filter theo level & chủ đề con.

Mở danh sách Golang