我有一個(gè)作為參數(shù)的方法v ...interface{},我需要在這個(gè)切片前面加上一個(gè)string. 這是方法:func (l Log) Error(v ...interface{}) { l.Out.Println(append([]string{" ERROR "}, v...))}當(dāng)我嘗試append()它不起作用時(shí):> append("some string", v)first argument to append must be slice; have untyped string> append([]string{"some string"}, v)cannot use v (type []interface {}) as type string in append在這種情況下預(yù)先準(zhǔn)備的正確方法是什么?
1 回答

慕的地6264312
TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超6個(gè)贊
append() 只能附加與切片元素類型匹配的類型的值:
func append(slice []Type, elems ...Type) []Type
因此,如果您有元素 as []interface{},則必須將首字母包裝string在 a[]interface{}中才能使用append():
s := "first"
rest := []interface{}{"second", 3}
all := append([]interface{}{s}, rest...)
fmt.Println(all)
輸出(在Go Playground上試試):
[first second 3]
- 1 回答
- 0 關(guān)注
- 243 瀏覽
添加回答
舉報(bào)
0/150
提交
取消