栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Go 方法中的默认值

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Go 方法中的默认值

不,但还有一些其他选项可以实现默认值。关于这个主题有一些很好的博客文章,但这里有一些具体的例子。

选项 1: 调用方选择使用默认值

// Both parameters are optional, use empty string for default valuefunc Concat1(a string, b int) string {  if a == "" {    a = "default-a"  }  if b == 0 {    b = 5  }  return fmt.Sprintf("%s%d", a, b)}

选项 2: 末尾的单个可选参数

// a is required, b is optional.// only the first value in b_optional will be used.func Concat2(a string, b_optional ...int) string {  b := 5  if len(b_optional) > 0 {    b = b_optional[0]  }  return fmt.Sprintf("%s%d", a, b)}

选项 3: 配置结构

// A declarative default value syntax// Empty values will be replaced with defaultstype Parameters struct {  A string `default:"default-a"` // this only works with strings  B string // default is 5}func Concat3(prm Parameters) string {  typ := reflect.TypeOf(prm)  if prm.A == "" {    f, _ := typ.FieldByName("A")    prm.A = f.Tag.Get("default")  }  if prm.B == 0 {    prm.B = 5  }  return fmt.Sprintf("%s%d", prm.A, prm.B)}

选项 4: 全可变参数解析(javascript 风格)

func Concat4(args ...interface{}) string {  a := "default-a"  b := 5  for _, arg := range args {    switch t := arg.(type) {      case string:        a = t      case int:        b = t      default:        panic("Unknown argument")    }  }  return fmt.Sprintf("%s%d", a, b)}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/660249.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号