[Golang] Introduction of Functions

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
}


<<:  Day 03 - 行前说明 — 在 MVC & MVVM 的 UI 元件

>>:  Day 4 如何规划拟定隐私三宝

DeBug Day 26

修正Bug日 [ ] 修正首页的排版问题 [ ] 修正书本细节页面的排版问题 [ ] 修正新增照片到...

Day 26-制作购物车之设定Redux: reducers&store

主要呈现实作成果 以下内容有参考教学影片,底下有附网址。 (内容包括我的不专业解说分析及在实作过程中...

【演算法】L1 演算法评估

演算法评估 ### 演算法衡量 效率 渐进符号 EX:O(n) 最差案例 平均案例 平摊分析 问题衡...

Day28 Java 注解

●Java 自定义注解 创建自定义注解类似於编写接口,不同之处在於interface关键字以@符号为...

DAY24 搞样式--用CSS Gird来搞个万年历吧(上)

前言 今天开始实作的部分,尝试用完全没碰过的CSS Grid要搞出一个万年历,不停的研究不停地开发新...