[Golang] func and . . .

golang func and . . .

  • 多個回傳值
  • 範例
    func main() {
    	foo()
    	bar("James")
    	s1 := woo("Moneypenny")
    	fmt.Println(s1)
    	x, y := mouse("Ian", "Fleming")
    	fmt.Println(x)
    	fmt.Println(y)
    }
    
    func foo() {
    	fmt.Println("hello from foo")
    }
    
    func bar(s string) {
    	fmt.Println("Hello,", s)
    }
    
    func woo(st string) string {
    	return fmt.Sprint("Hello from woo, ", st)
    }
    
    func mouse(fn string, ln string) (string, bool) {
    	a := fmt.Sprint(fn, " ", ln, `, says "Hello"`)
    	b := true
    	return a, b
    
    }
    

     

  • 傳入值可為 variadic parameter (https://golang.org/ref/spec#Lexical_elements) ,分類為 Lexical elements 中的 operators and punctuation
  • 範例
    func main() {
    	x := sum(2, 3, 4, 5, 6, 7, 8)
    	fmt.Println("The total is", x)
    }
    
    func sum(x ...int) int {
    	fmt.Println(x)
    	fmt.Printf("%T\n", x)
    
    	sum := 0
    	for i, v := range x {
    		sum += v
    		fmt.Println("for item in dex position,", i, "we are now adding,", v, "to the total which is now,", sum)
    	}
    
    	return sum
    }
    
  • 你也可以自己宣告 一個int的slice Ex. []int,然後用 . . . 傳入
  • func main() {
    	xi := []int{2, 3, 4, 5, 6, 7, 8}
    	x := sum(xi...)
    	fmt.Println("The total is", x)
    }
    
    func sum(x ...int) int {
    	fmt.Println(x)
    	fmt.Printf("%T\n", x)
    
    	sum := 0
    	for i, v := range x {
    		sum += v
    		fmt.Println("for item in dex position,", i, "we are now adding,", v, "to the total which is now,", sum)
    	}
    
    	return sum
    }

     

  • End