go 判断断言的类型是否为自定义结构体
在 go 中,断言可以确定某个表达式的类型。不过,对于自定义的结构体,在使用断言时可能会遇到一些问题。
如题所述代码所示,在 /model/model.go 文件中定义了 file 和 textfile 两个自定义的结构体,并在 /main.go 文件中使用断言来检查 templateargs 中的元素是否为 textfile。然而,代码中以下断言会报错:
config.templateargs["file"].(textfile).content = string(content)
原因是断言的类型是 textfile 结构体,但 config.templateargs["file"] 的类型并不是 textfile,因此会触发编译时错误。
正确的解决方案是用 file 类型来代替 textfile 类型进行断言,同时重新赋值:
config.templateargs["file"] = textfile{ file: config.templateargs["file"].(file), content: string(content), }
另外,也可以使用指针来重新赋值:
config.TemplateArgs["file"].(*TextFile).Content = string(content)
这样就可以正确地将 content 字段的值赋值给 templateargs 中的 textfile 结构体。
以上就是Go 中如何使用断言判断自定义结构体?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号