需要帮助将数据存储在数组结构中。

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

Need help in storing in the array struct

问题

我是一个编程初学者,现在正在学习Go语言,这个问题可能很简单。我有一个声明如下的变量:

var list []struct {
    Name    string
    Value string
}

问题是我不知道如何在其中初始化一个变量。感谢任何帮助。

我尝试过:

list[0].Name="12"
list[0].Value="123"
// 这会抛出一个索引超出范围的异常..
英文:

I m a beginner in programming and right now I'm learning go lang and this question might be simple. I have a declaration as follows:

var list []struct {
    Name    string
    Value string
}

The problem is I don't know how to initialize a variable inside this. Appreciate any help.

I have tried

    list[0].Name="12"
    list[0].Value="123"
    // this throws an index out of range exception..

答案1

得分: 3

首先,在主范围之外声明一个结构体类型:

type myStruct struct {
   Name  string
   Value string
}

然后,你告诉Go语言:"我想要一个包含这个结构体的x个元素的切片":

list := make([]myStruct, 5)

接下来,你只需使用正确的索引填充你的结构体:

list[0].Name = "12"
list[0].Value = "123"
英文:

Firstly you have to declare a type of struct outside of the main scope :

type myStruct struct {
   Name  string
   Value string
}

Then you say to go, "i want an slice of x of this struct" :

list := make([]myStruct, 5)

Then you just fill your struct with the right index :

list[0].Name = "12"
list[0].Value = "123"

答案2

得分: 0

以下是您要翻译的内容:

以下方法可能是您正在寻找的方法。

package main
import "fmt"

type YourType struct {
    Name, Value string
}

var ListOfTypes = []YourType{
    {Name: "NameOne", Value: "ValueOne"},
    {Name: "NameTwo", Value: "ValueTwo"},
}

func main() {
    fmt.Println(ListOfTypes[0]) // 这将打印 {NameOne ValueOne}
    ListOfTypes[0].Name = "NewValue"
    fmt.Println(ListOfTypes[0]) // {NewValue ValueOne}
}
英文:

Following approach might be the one you are looking.

package main
import ("fmt")
type YourType struct {
	Name, Value string
}
var ListOfTypes=[]YourType{
	{Name:"NameOne",Value:"ValueOne"},
	{Name:"NameTwo",Value:"ValueTwo"},
}
func main() {
	fmt.Println(ListOfTypes[0]) // This will print {NameOne ValueOne}
	ListOfTypes[0].Name="NewValue"
	fmt.Println(ListOfTypes[0]) //{NewValue ValueOne}
}

huangapple
  • 本文由 发表于 2016年11月15日 14:52:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/40603752.html
匿名

发表评论

匿名网友

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

确定