iT邦幫忙

2021 iThome 鐵人賽

DAY 7
0
DevOps

"GoDevOps": Learn DevOps Tools with Go系列 第 7

[Golang] Introduction of Functions

  • 分享至 

  • xImage
  •  

Declairing Functions

We can use the func keyword to declair a function as following:

https://ithelp.ithome.com.tw/upload/images/20210918/20130321goZJzwSHme.png

The input parameters and return type(s) are optional, such as func main(). Besides, a function can return multiple values as well. For example:

package main

import (
	"errors"
	"fmt"
)

func main() {
	hello()

	rate, _ := getRate(53, 100)
	fmt.Println(rate, "%")
}

func hello() {
	fmt.Println("Hello world")
}

func getRate(numerator int, denominator int) (float64, error) {
	if denominator <= 0 {
		err := errors.New("denominator cannot be zero or negative")
		return 0.0, err
	}

	rate := float64(numerator) / float64(denominator) * 100
	return rate, nil
}

On above example, we return an error type value to indicate an abnormal situation and use blank identifier _ to ignore some of the results from a function that returns multiple values.

We can put functions to another go file as well. For example:

utils.go

package main

import "fmt"

func hello() {
	fmt.Println("Hello world")
}

main.go

package main

func main() {
	hello()
}

Then you can run command "go run *.go" to test the result

$ go run *.go
Hello world

Be Aware of Slices Type Parameter.

As we mention in previous blog, slice is pass by reference.
When you change the value of a slice type parameter inside the function,
The value outside the function is changed as well.

for example:

package main

import "fmt"

func main() {

	x := [5]int{5, 4, 3, 2, 1}
	y := []int{5, 4, 3, 2, 1}
	reset(x, y)
	fmt.Println(x) //output = [5 4 3 2 1]
	fmt.Println(y) //output = [0 4 3 2 1]
}

func reset(a [5]int, s []int) {
	a[0] = 0
	s[0] = 0
}


上一篇
[Golang] Array and Slice
下一篇
[Golang] Modules
系列文
"GoDevOps": Learn DevOps Tools with Go11
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言