Basic Function Declarations in Go
As in other programming languages, there are various ways to declare and call functions in Go. Here are some examples:
The Func
func foo() {
// Do something
}
func foo(bar string) {
fmt.Println(bar)
}
Functions start with the keyword
func
Variables are optional, but a type should be specified if there is one
Arguments
func foo(bar string, baz string) {
fmt.Println(bar + baz)
}
func foo(bar, baz string) {
fmt.Println(bar + baz)
}
Arguments should come with a type
Multiple arguments can be assigned to the same type
func foo(bar ...string) {
for i := 0; i < len(bar); i++ {
fmt.Println(bar[i])
}
}
func foo(bar int, baz ...int) {
// Do something
}
...
means multiple arguments are possibleWhen multiple arguments are assigned, it becomes an array in the function
One or more arguments are allowed to come before the multiple arguments assignment
Returned Values
func foo() string {
return "bar"
}
Returned values are not necessary
If any value is returned, a type should be specified
func foo() (bar string) {
bar = "buz"
return
}
A variable can be assigned to the returned value
Returned values should be in the parantheses
If
bar
is assigned as a returned value, it is already declared, no need to dobar := "something"
againIf
bar
is assigned,return
will automatically returnbar
Custom Types
type Foobar struct {
Foo string
Bar string
}
func Baz(foobar Foobar) (bazqux Foobar) {
bazqux.Foo = foobar.Foo
bazqux.Bar = foobar.Bar
return
}
Assigning a custom type as a argument or returned value is possible
Methods
When functions are binded to a struct, it becomes a method.
type Foobar struct {
Foo string
Bar string
}
func (f Foobar) Baz() {
fmt.Println(f.Foo)
}
It works like an instance method in Ruby while we can initiate like
foo := Foobar
and callfoo.Baz()
f
represents the instance in the function