为了账号安全,请及时绑定邮箱和手机立即绑定

使用要在运行时填充的字符串切片

使用要在运行时填充的字符串切片

Go
温温酱 2021-04-10 15:10:35
我觉得有点傻,因为这应该很容易,但是我只是从go开始,无法弄清楚。package mainimport "fmt"type Question struct { q []string a []string}func (item *Question) Add(q string, a string) { n := len(item.q) item.q[n] := q item.a[n] := a}func main() { var q Question q.Add("A?", "B.")}编译时会出现错误:q.go:11:12:错误:预期为';' 或'}'或换行符q.go:12:12:错误:预期为';' 或'}'或换行符指的是item.q [n]的开头大括号:= q和下一行。我敢肯定我使用的分片不正确,因为它可以与一个简单的字符串一起正常工作,但是我不确定如何解决它。编辑:我已经按照Pat Notz的建议使用StringVectors重新实现了它,并且效果很好。以下是工作代码:package mainimport (    fmt "fmt"    vector "container/vector")type Question struct {    q vector.StringVector    a vector.StringVector}func (item *Question) Add(q string, a string) {    item.q.Push(q)    item.a.Push(a)}func (item *Question) Print(index int) {    if index >= item.q.Len() {        return    }    fmt.Printf("Question: %s\nAnswer: %s\n", item.q.At(index), item.a.At(index))}func main() {    var q Question    q.Add("A?", "B.")    q.Print(0)}
查看完整描述

3 回答

?
饮歌长啸

TA贡献1951条经验 获得超3个赞

切片只是数组的视图,而不是实际的数组。根据您的代码片段,我认为您想StringVectorcontainer/vector软件包中使用它。这实际上是动态调整大小的数组的唯一选择。内置数组的大小固定。如果您事先知道要存储多少个元素,它们也可以正常工作。


查看完整回答
反对 回复 2021-04-26
?
守候你守候我

TA贡献1802条经验 获得超10个赞

您不应该使用:=中的item.q[n] := q

:= 仅在必须分配给新变量时使用。

在这种情况下,您只需要使用 item.q[n] = q

使用切片而不是容器/向量也是更好的选择。go(1.0.3)不再支持vector。

将项目附加到切片的更好方法是

slice = append(slice, new_item_1,item_2,item_3)


查看完整回答
反对 回复 2021-04-26
  • 3 回答
  • 0 关注
  • 203 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信