iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 10
0
自我挑戰組

Go to 放棄系列 第 10

go note 5 =>回傳

  • 分享至 

  • xImage
  •  

return value

package main

import (
	"fmt"
)

func swap(i, j int) (int, int) {
	return j, i
}

func main() {
	a := 1
	b := 2
	a, b = swap(a, b)

	fmt.Println("a: ", a)
	fmt.Println("b: ", b)
}

等同
a, b = b, a

return function

package main

import (
	"fmt"
)

func test() func() int {
	return func() int {
		return 99
	}
}

func main() {
	bar := test()
	fmt.Printf("%T\n", bar) // %T為型態,印出型態
	fmt.Println(bar())
	fmt.Println(test()) // 印出test裡的那個function位址

  test2 := func(i, j float32) float32 {
    return i + j
  }
	fmt.Printf("%T\n", test2) // %T為型態,印出型態
	fmt.Println(test2())
	fmt.Println(test2()) // 印出test裡的那個function位址
}

// func() int
// 99
// 0x8dd30
// func(float32, float32) float32
// 23.3

anonymous func(常使用在go routine)

package main

import (
	"fmt"
)

func main() {
	foo := func() string {
		return "Hello go"
	}
	fmt.Println(foo())
	bar := func() {
		fmt.Println("hello golang")
	}
	bar()
	func() {
		fmt.Println("golang go")
	}()
	go func(i, j int) {
		fmt.Println(i + j)
	}(1, 2)
}

func parameter

package main

import (
	"fmt"
	"strings"
)

func getUserListSQL(username, email string) string {
	sql := "select * from user"
	where := []string{}

	if username != "" {
		where = append(where, fmt.Sprintf("username = '%s'", username))
	}
	if email != "" {
		where = append(where, fmt.Sprintf("email = '%s'", email))
	}
	return sql + " where " + strings.Join(where, " or ")
}
func main() {
	fmt.Println(getUserListSQL("roy", ""))
	fmt.Println(getUserListSQL("roy", "roy@gmail.com"))
}

https://ithelp.ithome.com.tw/upload/images/20181025/20112477azCrAZqjjZ.png

使用struct

package main

import (
	"fmt"
	"strings"
)

type searchOpts struct {
	username string
	email    string
	sex      int
}

func getUserListOptsSQL(opts searchOpts) string {
	sql := "select * from user"
	where := []string{}

	if opts.username != "" {
		where = append(where, fmt.Sprintf("username = '%s'", opts.username))
	}
	if opts.email != "" {
		where = append(where, fmt.Sprintf("email = '%s'", opts.email))
	}
	if opts.sex != 0 {
		where = append(where, fmt.Sprintf("sex = '%d'", opts.sex))
	}
	return sql + " where " + strings.Join(where, " and ")
}
func main() {
	fmt.Println(getUserListOptsSQL(searchOpts{
		username: "roy",
		email:    "roy@gmail.com",
		sex:      1,
	}))
}

上一篇
go note4=>宣告
下一篇
go note6 -> 錯誤處理
系列文
Go to 放棄30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言