加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang中interface{}作为函数参数和函数返回值的使用

发布时间:2020-12-16 19:19:20 所属栏目:大数据 来源:网络整理
导读:Golang中interface{}作为函数参数和函数返回值的使用 下面给出一个例子: package mainimport ( "errors" "fmt")type item struct { Name string}func (i item) String() string { return fmt.Sprintf("item name: %v",i.Name)}type person struct { Name st
Golang中interface{}作为函数参数和函数返回值的使用

下面给出一个例子:

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{"zhangsan","man"}).(*person)
    fmt.Println(p2)
}

输出结果:
item name: Apple
person name: zhangsan sex: man
成功: 进程退出代码 0.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读