drkxgs9358 2019-04-01 00:39
浏览 90
已采纳

如何转换结构字段名称中的任何字符串,例如

I would like to know if there is a native way to transform strings like:

  • a.string
  • a-string
  • a_string
  • a string

In a string that follows the convention for public field members of structs, in Go.

The idea is to write a function that accepts a string and try to get the value of the field, even if the passed string is not using the PascalCase convention, example:

type MyStruct struct {
    Debug   bool
    AString bool
    SomethingMoreComplex
}

var myStruct MyStruct

func GetField(s string) reflect.Value {
   v := reflect.ValueOf(myStruct)
   return v.FieldByName(s)
}

function main() {
    GetField("debug")
    GetField("a.string")
    GetField("a-string")
    GetField("a_string")
    GetField("-a.string")
    GetField("something-more-complex")
}

I was using the strcase package, but it only works for ASCII.

  • 写回答

2条回答 默认 最新

  • duanchui1279 2019-04-01 01:47
    关注

    By the magic of regular expressions

    https://goplay.space/#xHfxG249CsH

    package main
    
    import (
        "fmt"
        "regexp"
        "strings"
    )
    
    func ConvertFieldName(s string) string {
        r := regexp.MustCompile("(\\b|-|_|\\.)[a-z]")
        return r.ReplaceAllStringFunc(s, func(t string) string {
            if len(t) == 1 {
                return strings.ToUpper(t)
            } else {
                return strings.ToUpper(string(t[1]))
            }
    
        })
    
    }
    
    func main() {
        fmt.Println(ConvertFieldName("debug"))
        fmt.Println(ConvertFieldName("a.string"))
        fmt.Println(ConvertFieldName("a-string"))
        fmt.Println(ConvertFieldName("a_string"))
        fmt.Println(ConvertFieldName("-a.string"))
        fmt.Println(ConvertFieldName("something-more-complex"))
    }
    

    Outputs

    Debug
    AString
    AString
    AString
    AString
    SomethingMoreComplex
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c