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

发布于 2024-08-21 08:25:46 字数 1115 浏览 10 评论 0原文

我觉得有点傻,因为这应该是一个简单的问题,但是我刚刚开始使用 go 并且无法弄清楚。

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.")
}

编译时出现错误:

q.go:11:12: error: expected ';' or '}' or newline
q.go:12:12: error: expected ';' or '}' or newline

that 引用了 item.q[n] := q 的左大括号和以下行。

我确信我错误地使用了切片,因为它可以很好地使用简单的字符串,但我不确定如何修复它。

编辑:我已经按照 Pat Notz 的建议使用 StringVectors 重新实现了它,并且效果很好。以下是工作代码:

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)
}

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

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.")
}

When Compiling it gives the errors:

q.go:11:12: error: expected ';' or '}' or newline
q.go:12:12: error: expected ';' or '}' or newline

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.

edit: I have re-implemented it using StringVectors as per Pat Notz's advice and it works well. The following is the working 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)
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

老旧海报 2024-08-28 08:25:46

切片只是数组的一个视图——而不是一个实际的数组。根据您的代码片段,我认为您想使用 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.

乞讨 2024-08-28 08:25:46

问题出在 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

铜锣湾横着走 2024-08-28 08:25:46

通过将切片委托给 StringVector,您避免了使用切片时遇到的问题。我修改了您最初的实现(使用字符串切片),使其成为有效的工作程序。

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

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

var q Question

声明 q,为 Question 结构分配存储空间,并将结构字段(切片 qq 和 qa)初始化为零,即切片指针为零,切片 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 "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)
}
撑一把青伞 2024-08-28 08:25:46

您不应该像 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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文