登录
首页 >  Golang >  Go问答

如何在 Golang 中更新类型开关的结构体字段?

来源:stackoverflow

时间:2024-02-08 21:21:22 321浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《如何在 Golang 中更新类型开关的结构体字段?》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

我想创建一个函数,接受不同的商品结构并加密它们的 id。 我有一个加密功能:

func encryption(in string, typeof string) string {
    result := in + typeof
    return result
}

和2个商品结构:

type cloth struct {
    clothid   string
    name string
}

type pants struct {
    pantsid   string
    name string
}

我想通过一个函数来修改它们,通过传入可变参数,来执行不同的操作,那就应该修改struct的id

func encryptid(in interface{}) {
    switch in.(type) {
    case cloth:
        in.clothid = encryption(in.clothid, "cloth")
    case pants:
        in.pantsid = encryption(in.pantsid, "pants")
    default:
        return
    }
}

但是这个函数虽然可以判断类型,但是不能修改类型,怎么办?

我在网上找到了这些,但只能判断,不能修改。 我希望这样做之后

func main() {
    clo := cloth{"cloth", "blue"}
    pan := pants{"pants", "green"}
    encryptId(clo)
    encryptId(pan)
    fmt.Println(clo)
    fmt.Println(pan)
}

它将输出

{布蓝} {裤子绿色}


正确答案


由 mkopriva 解决

func encryptId(in interface{}) {
    switch s := in.(type) {
    case *cloth:
        s.id = encryption(s.id, "key")
    case *pants:
        s.id = encryption(s.id, "key")
    default:
        return
    }
}
 
func main() {
    clo := cloth{"cloth", "blue"}
    pan := pants{"pants", "green"}
    encryptId(&clo)
    encryptId(&pan)
    fmt.Println(clo)
    fmt.Println(pan)
}

今天关于《如何在 Golang 中更新类型开关的结构体字段?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>