//有返回值 且返回一个
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 bool
var val int
val, err = m[key]
return val, err
}
//多个参数,相当于传进取一个数组
func sum(nums ...int) {
fmt.Println(nums, " ")
total := 0
for _, num := range nums {
total += num
}
fmt.Println(total)
}
//返回值为函数
func nextNum() func() int {
i, j := 0, 1
return func() int {
var tmp = i + j
i, j = j, tmp
return tmp
}
}
//递归 返回整数
func fact(n int) int {
if n == 0 {
return 1
}
return n * fact(n-1)
}
//结构
type rect struct {
width float64
height 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() float64
perimeter() 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 int
errMsg 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)
}
有疑问加站长微信联系(非本文作者)