Functions
On the surface, Go functions are exactly the same as in any other programming language: a section of code designed to perform a certain task grouped into a re-usable container. Thanks to the static nature of the language, all functions have a signature that defines the number and types of acceptable input arguments and output values.
Consider the following function (generateName
) that generates a new name based on a pair of input strings (base
, suffix
). You can find the full code of the next example at ch03/functions1/main.go
.
func generateName(base string, suffix string) string {
parts := []string{base, suffix}
return strings.Join(parts, "-")
}
func main() {
s := generateName("device", "01")
// prints "device-01"
fmt.Println(s)
}
This function’s signature is func (string, string)
string, meaning that it accepts two arguments of type string and returns another string. You can assign the returned value to...