When declaring function parameters in Go, you must type the incoming data. Here’s an example:
package main
import "fmt"
func print_stuff(s string) {
fmt.Println(s)
}
func main() {
print_stuff("Passing string!")
}
s string
indicates that we’re passing a variable of type string
into the function. This prevents us from from passing into variables of any other type. For example, this will fail with ./prog.go:10:17: cannot use 42 (type untyped int) as type string in argument to example_str
if you try to pass an integer.
package main
import "fmt"
func print_stuff(s string) {
fmt.Println(s)
}
func main() {
print_stuff(42) // Fails!
}
Empty Go interfaces can be used to accept any type of variable in a function.
package main
import "fmt"
func print_stuff(s interface{}) {
fmt.Println(s)
}
func main() {
print_stuff(42) // Now works fine!
}
Typically you should properly type your variables, but in some cases (where you cannot know the type of data ahead of time), this can be useful.
fmt.Println() is a good example of this.