Functions in Go

 Functions in Go


In Go, you declare a function using the func keyword followed by the function name, the parameter list, and the return type.



func add(a, b int) int {

    return a + b

}

Functions can also return multiple values, and you can assign the return values to separate variables using a multi-variable assignment.



func divide(a, b float64) (float64, error) {

    if b == 0 {

        return 0, errors.New("division by zero")

    }

    return a / b, nil

}


result, err := divide(10.0, 2.0)

if err != nil {

    fmt.Println(err)

} else {

    fmt.Println(result)

}

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...