以下问题有多种答案/技巧:
我有几个答案,但需要进一步讨论.
我有一个结构ProductData及其实例p,它有一个slice属性:
type ProductInfo struct {
TopAttributes []map[string]interface{}
}
Run Code Online (Sandbox Code Playgroud)
我想设置TopAttributes如下
func (p *ProductInfo) setAttributeData() {
key := "key"
value := "value"
setAttribute(p.TopAttributes, key, value)
}
func setAttribute(p []map[string]interface{}, key string, value interface{}) {
val := map[string]interface{}{
key: value,
}
p = append(p, val)
}
Run Code Online (Sandbox Code Playgroud)
但是,当我将方法定义为:时,还有另一种方法可以正常工作:
func (p *ProductInfo) setAttributeData() {
key := "key"
value := "value"
p.setAttribute(key, value)
}
func (p *ProductInfo) setAttribute(key string, value interface{}) {
val := map[string]interface{}{
key: value,
}
p.TopAttributes = append(p.TopAttributes, val)
}
Run Code Online (Sandbox Code Playgroud)
我想找出它为什么不起作用.我的代码中没有错误,但数据是空的.我试图这样做使它成为一个泛型函数,因为我有另一个BottomAttributes必须以相同的方式设置.
我有一些我要映射的数据[]string
.我可以用两种方式做到:
一个)
// someData
s := someData.([]string)
Run Code Online (Sandbox Code Playgroud)
在这种情况下,执行将在控制台上列出错误后停止.
b)
// someData
s, ok := someData.([]string)
Run Code Online (Sandbox Code Playgroud)
在这种情况下,不会发生错误,但s将具有零值
我想在不停止执行的情况下在这种类型的断言失败案例中记录错误.但是,当我使用类型(b)时,我看不到错误详细信息.
我能想到的唯一解决方案是使用reflect.TypeOf
和打印两种类型.
使用解决方案(b)时,还有其他方法可以解决错误吗?
当我在golang body param的http.NewRequest中传递字符串时,我遇到了一个问题.
我得到的错误是:
不能使用req.Body(类型字符串)作为http.NewRequest参数中的类型io.Reader:string不实现io.Reader(缺少Read方法)
类似地,还有其他用例需要将Buffer作为输入而不是特定类型或其数组.例如,当需要输入是缓冲区时,byte [].
错误是什么意思,解决问题的方法是什么,以及了解golang试图强制执行的内容.
编辑:这是我遇到问题的一行,没有找到任何参考.
http.NewRequest(req.Method,req.Url,req.Body)
http.NewRequest(req.Method,req.Url,strings.NewReader(req.Body))解决了这个问题.我还计划添加答案(作为FYI类型的问题)