通过参考作为参数传递不同类型的变量,将变量转换为同一variadic参数
我一直在与 golang 缺乏可选参数的困难,所以我一直在使用最接近的解决方法:variadics。即使我使它起作用,但试图通过参考将多种变量类型传递到相同的variadic参数是凌乱的:
// back-end
func UpdateRef(variadic ...*interface{}) {
for _, v := range variadic {
if v.(type) == string {
*v = "New ref val"
}
}
}
// front-end
func Interface(x interface{}) interface{} { return &x }
func main() {
ref := Interface("Hey") // starts as "Hey"
i := Interface(500)
UpdateRef(&ref, &i) // ends at "New ref val"
}
替换前端
// front-end
func main() {
ref := "Hey" // starts as "Hey"
UpdateRef(ref, 500) // ends at "New ref val"
}
如果我用以下方式 前端代码工作?只要所需的前端运行,后端就可以像需要一样详细。这可能吗?如果没有,是否需要一种优雅的解决方案,需要对所需的前端进行最小的变化?
I've been struggling with golang's lack of optional parameters, so I have been using the closest workaround: variadics. Even though I got it working, it is messy attempting to pass multiple variable types to the same variadic parameter by reference:
// back-end
func UpdateRef(variadic ...*interface{}) {
for _, v := range variadic {
if v.(type) == string {
*v = "New ref val"
}
}
}
// front-end
func Interface(x interface{}) interface{} { return &x }
func main() {
ref := Interface("Hey") // starts as "Hey"
i := Interface(500)
UpdateRef(&ref, &i) // ends at "New ref val"
}
If I replace the front-end with this:
// front-end
func main() {
ref := "Hey" // starts as "Hey"
UpdateRef(ref, 500) // ends at "New ref val"
}
...then how could I change the back-end to make the desired front-end code work? The back-end can be as verbose as need be, so long as the desired front-end runs as is. Is this possible? If not, is there an elegant solution that requires minimal changes to the desired front-end?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
接口{}
作为参数类型。键入指针类型。取消指针设置值。
将指针传递到功能:
Use
interface{}
as the argument type. Type assert to pointer types.Dereference pointers to set the values.
Pass pointers to the function:
您只需
查看Golang博客: https://go.dev/blog/laws/laws-og/laws-og-laws-er-laws-er-laws-of--------反射。
编码快乐!
you just
check out the golang blog:https://go.dev/blog/laws-of-reflection.
Coding Happy!