Golang Basic 7 - Function

Golang Basic 7 - Function

Function

Function Declear

  • A function can take zero or more arguments.
  • Notice that the type comes after the variable name.
    golang
    func functionName(input_var1 DataType, input_var2 DataType) retDataType{
    // some code block here.
    return retData
    }

Call a function

functionName(input_var1, input_var2)

Sample

root@go:/develop/go/l7# cat l7s1.go
package main
import (
    "fmt"
)

func add(x int, y int) int{
    return x   y

}

func main(){
    fmt.Println(add(1, 2))

}
root@go:/develop/go/l7# go run l7s1.go
3

Same Parameters' Type

  • If all the parameters have the same data type, we can omit the type from all but the last.
func add(x, y int) int{
    return x   y
}

Sample

root@go:l7/ # cat l7s2.go
package main
import (
    "fmt"
)

func add(x , y int) int{
    return x   y

}

func main(){
    fmt.Println(add(1, 2))

}
root@go:l7/ # go run l7s2.go
3

Multi Return Values

func functionName(input_var1 DataType, input_var2 DataType) retDataType1, retDataType2{
    // some code block here.
    return retData1, retData2
}

Sample

root@go:l7/ # cat l7s3.go
package main
import (
    "fmt"
)

func swap(x , y int) (int, int){
    return y, x

}

func main(){
    var var1, var2 int = swap(1, 2)
    fmt.Println(var1, var2)

}
root@go:l7/ # go run l7s3.go
2 1

Named Return Values

func functionName(input_var1 DataType, input_var2 DataType) variableName1 DataType, variableName2 DataType{
    // some code block here.
    var variableNamel DataType = ...
    var variableName2 DataType = ...
    return
}

Sample

root@go:l7/ # cat l7s4.go
package main
import (
    "fmt"
)

func getAnswer(x , y int) (add int, div float64){
    add = x   y
    div = float64(x) / float64(y)
    return

}

func main(){
    var var1 int
    var var2 float64
    var1, var2 = getAnswer(5, 2)
    fmt.Println(var1, var2)

}
root@go:l7/ # go run l7s4.go
7 2.5

发表评论

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据