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

huangapple go评论92阅读模式
英文:

Using a string slice that is to be filled at runtime

问题

我感觉有点傻,因为这应该是一个简单的问题,但是我刚开始学习Go语言,无法弄清楚。

<pre><code>package main

import "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.")
}</code></pre>

编译时出现以下错误:
<pre>q.go:11:12: 错误: 期望 ';' 或 '}' 或换行符
q.go:12:12: 错误: 期望 ';' 或 '}' 或换行符</pre>

这些错误指的是item.q[n] := q的大括号和下一行。

我确定我在使用切片时出错了,因为如果只使用简单的字符串,它可以正常工作,但是我不知道如何修复它。

<b>编辑:根据Pat Notz的建议,我已经重新实现了它,使用了StringVectors,并且它工作得很好。以下是可工作的代码:</b>

<pre><code>package main

import (
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)
}
</code></pre>

英文:

I feel a little silly as this should be an easy one, however I just started with go and can't figure it out.

<pre><code>package main

import "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.")
}</code></pre>

When Compiling it gives the errors:
<pre>q.go:11:12: error: expected ';' or '}' or newline
q.go:12:12: error: expected ';' or '}' or newline</pre>

that refers to the opening brace of item.q[n] := q and the following line.

I'm certain that I'm using slices incorrectly as it works fine with a simple string instead, but I'm not sure how to fix it.

<b>edit: I have re-implemented it using StringVectors as per Pat Notz's advice and it works well. The following is the working code:</b>

<pre><code>package main

import (
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)
}
</code></pre>

答案1

得分: 2

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

英文:

A slice is simply a view into an array -- not an actual array. Based on your code snippet I think you want to use StringVector from the container/vector package. That's really your only choice for dynamically sized arrays. The built in arrays have a fixed size. They'd work fine too if you know in advance how many elements you want to store.

答案2

得分: 1

问题出在Add方法中--当你给切片的一个元素赋值时,应该使用'='而不是':='

func (item *Question) Add(q string, a string) {
 n := len(item.q)
 item.q[n] = q
 item.a[n] = a
}

:=操作符只用于声明新变量。

英文:

The problem is in the Add method -- when you assign an element of a slice, you should use '=' instead of ':='

func (item *Question) Add(q string, a string) {
 n := len(item.q)
 item.q[n] = q
 item.a[n] = a
}

The := operator is only used for declaring new variables

答案3

得分: 0

你通过将问题委托给StringVector来解决使用切片时遇到的问题。我已经修改了你最初的实现,该实现使用了字符串切片,使其成为一个有效的、可工作的程序。

type Question struct {
    q   []string
    a   []string
}

Question类型是一个结构体,它有两个元素q和a,它们是字符串数组的切片。切片隐式地包含指向开始切片的数组元素的指针,切片的长度和切片的容量。

var q Question

声明了q,为Question结构体分配了存储空间,并将结构体字段(切片q.q和q.a)初始化为零,即切片指针为nil,切片的len()和cap()函数返回零。没有为字符串数组分配存储空间;我们需要单独做这个。

package main

import "fmt"

type Question struct {
    q   []string
    a   []string
}

func addString(ss []string, s string) []string {
    if len(ss)+1 > cap(ss) {
        t := make([]string, len(ss), len(ss)+1)
        copy(t, ss)
        ss = t
    }
    ss = ss[0 : len(ss)+1]
    ss[len(ss)-1] = s
    return ss
}

func (item *Question) Add(q string, a string) {
    item.q = addString(item.q, q)
    item.a = addString(item.a, a)
}

func main() {
    var q Question
    q.Add("A?", "B.")
    fmt.Println("Q&A", q)
}
英文:

You sidestepped the problems you were having using slices by delegating them to StringVector. I've revised your initial implementation, which used string slices, to become a valid, working program.

type Question struct {
    q   []string
    a   []string
}

The type Question is a struct which has two elements, q and a, which are slices of an array of strings. A slice implicitly contains a pointer to the element of the array which begins the slice, the length of the slice, and the capacity of the slice.

var q Question

declares q, allocating storage for the Question struct, and initializes the struct fields (slices q.q and q.a) to zero i.e. the slice pointers are nil, and the slice len() and cap() functions return zero. No storage is allocated for string arrays; we need to do that separately.

package main

import &quot;fmt&quot;

type Question struct {
    q   []string
    a   []string
}

func addString(ss []string, s string) []string {
    if len(ss)+1 &gt; cap(ss) {
        t := make([]string, len(ss), len(ss)+1)
        copy(t, ss)
        ss = t
    }
    ss = ss[0 : len(ss)+1]
    ss[len(ss)-1] = s
    return ss
}

func (item *Question) Add(q string, a string) {
    item.q = addString(item.q, q)
    item.a = addString(item.a, a)
}

func main() {
    var q Question
    q.Add(&quot;A?&quot;, &quot;B.&quot;)
    fmt.Println(&quot;Q&amp;A&quot;, q)
}

答案4

得分: 0

你不应该使用 :=,例如 item.q[n] := q

:= 只用于在需要赋值给新变量时使用。

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

还有,最好使用切片而不是容器/向量。go(1.0.3) 不再支持向量。

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

slice = append(slice, new_item_1,item_2,item_3)
英文:

You shouldnt be using := as in item.q[n] := q .

:= is only used when you have to assign to a new variable.

In this case, you just have to use item.q[n] = q

Its also better to use slices instead of container/vector. go(1.0.3) does not support vector anymore.

A better way to append an item to a slice is

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

huangapple
  • 本文由 发表于 2010年2月13日 15:50:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/2256875.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定