/有返回值 且返回一个func max(a int, b int) int {if a > b {return a}
return b}//有返回值 且返回二个func multi_ret(key string) (int, bool) {m := map[string]int{"ont": 1, "two": 2, "three": 3}var err boolvar val intval, err = m[key]return val, err}//多个参数,相当于传进取一个数组
func sum(nums ...int) {fmt.Println(nums, " ")total := 0for _, num := range nums {total += num}
fmt.Println(total)
}//返回值为函数
func nextNum() func() int {i, j := 0, 1return func() int {var tmp = i + ji, j = j, tmpreturn tmp}
}//递归 返回整数func fact(n int) int {if n == 0 {return 1}
return n * fact(n-1)}//结构
type rect struct {width float64height float64}//结构函数
func (r *rect) area() float64 {return r.width * r.height}func (r *rect) perimeter() float64 {return 2 * (r.height * r.height)}//结构
type circle struct {radius float64}func (c *circle) area() float64 {return math.Pi * c.radius * c.radius}func (c *circle) perimeter() float64 {return 2 * math.Pi * c.radius}//接口 注意rect和circle均实现了shape接口type shape interface {area() float64perimeter() float64}func interface_test() {r := rect{width: 2, height: 4}c := circle{radius: 4.3}s := []shape{&r, &c}for _, sh := range s {fmt.Println(sh)
fmt.Println(sh.area())
fmt.Println(sh.perimeter())
}
}//自定义错误
type myError struct {arg interrMsg string}func (e *myError) Error() string {return fmt.Sprintf("%d - %s", e.arg, e.errMsg)}func error_test(arg int) (int, error) {if arg < 0 {return -1, errors.New("Bad Arguments, negtive")} else if arg > 256 {return -1, &myError{arg, "Bad Arguments, too large"}}
return arg * arg, nil}func CopyFile(dstName string, srcName string) (written int64, err error) {src, err := os.Open(srcName)if err != nil {fmt.Println("open failed")}
defer src.Close()dst, err := os.Create(dstName)if err != nil {fmt.Println("Create failed")return}
defer dst.Close()return io.Copy(dst, src)}
查看原文:http://www.zoues.com/2016/10/27/golang-%e5%87%bd%e6%95%b0%e5%ae%9a%e4%b9%89%e5%8f%8a%e5%85%b6%e6%8e%a5%e5%8f%a3%e5%ae%9e%e4%be%8b/
有疑问加站长微信联系(非本文作者)