Func parameter and return value operation of golang

Time:2021-9-26

Parameters and return values

Parameter 1 specifies that the data type is int

Parameter 2 (… Interface {}) can pass any number of different types of parameters

Return value: a single return value directly specifies the data type. You can not use (). Multiple return values need to use (). Return values are separated by commas


func main() {
 demo.Params(10, 20, "golang", true)
}
func Params(id int, params ...interface{}) (error, error) {
 fmt.Println(id)
 fmt.Println(params[0])
 fmt.Println(params[1])
 fmt.Println(params[2])
 for key, val := range params {
  fmt.Println("key", key)
  fmt.Println("val", val, reflect.TypeOf(val))
 }
 return nil, errors.New("error")
}

Debug is as follows

image.png

Supplement: golang interface {} is used as an example of function parameters and function return values

Look at the code~


package main
import (
    "errors"
    "fmt"
)
type item struct {
    Name string
}
func (i item) String() string {
    return fmt.Sprintf("item name:%v", i.Name)
}
type person struct {
    Name string
    Sex  string
}
func (p person) String() string {
    return fmt.Sprintf("person name:%v sex:%v", p.Name, p.Sex)
}
func Parse(i interface{}) interface{} {
    switch i.(type) {
    case string:
        return &item{
            Name: i.(string),
        }
    case []string:
        data := i.([]string)
        length := len(data)
        if length == 2 {
            return &person{
                Name: data[0],
                Sex:  data[1],
            }
        } else {
            return nil
        }
    default:
        panic(errors.New("Type match miss"))
    }
    return nil
}
func main() {
    p1 := Parse("apple").(*item)
    fmt.Println(p1)
    p2 := Parse([]string{"zhanghan", "man"}).(*person)
    fmt.Println(p2)
    fmt.Println(p1.Name)
    fmt.Println(p2.Name)
    fmt.Println(p2.Sex)
}

The operation results are as follows:

item name:apple

person name:zhanghan sex:man

apple

zhanghan

man

The above is my personal experience. I hope I can give you a reference, and I hope you can support developpaer. If you have any mistakes or don’t consider completely, please don’t hesitate to comment.