create a function with a parameter in go

In Go, creating a function with a parameter is as simple as defining the function with the variable name and type in parentheses after the function name. Here's an example:

main.go
func add(x int, y int) int {
    return x + y
}
48 chars
4 lines

In this example, the function add takes two integer parameters (x and y) and returns their sum as an integer.

You can also define multiple parameters with the same type by separating them with commas:

main.go
func greet(firstName, lastName string) {
    fmt.Printf("Hello, %s %s!\n", firstName, lastName)
}
98 chars
4 lines

In this example, the greet function takes two parameters of type string (firstName and lastName) and prints a greeting to the console.

Now, you can call these functions and pass values to the parameters:

main.go
sum := add(3, 4) // sum is 7
greet("John", "Doe") // prints "Hello, John Doe!"
79 chars
3 lines

related categories

gistlibby LogSnag