创建结构体数组并初始化其中的元素时出现错误。

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

Error while creating array of struct and initializing elements in it

问题

我正在尝试创建一个包含两个元素的数组,但是出现了错误。

type TODO struct {
    Number int
    Task   string
}

func main() {
    var todoArr [2]TODO

    fE := &TODO{Number: 10, Task: "Task1"}
    sE := &TODO{Number: 11, Task: "Task2"}
    todoArr[0] = *fE
    todoArr[1] = *sE
}

无法将fE(类型为*TODO)用作TODO类型进行赋值

我不知道为什么会出现这个错误。另外,我想知道在Go语言中是否有一种简洁的方式来声明和初始化数组/切片,就像这样:

[]TODO{&TODO{Number: 10, Task: "Task1"}, &TODO{Number: 11, Task: "Task2"}}
英文:

i'm trying to create array with two elements in it but i got an error

 type TODO struct {
	Number             int
	Task               string
}

func main() {
	var todoArr [2]TODO

	fE := &TODO{Number: 10, Task: "Task1"}
	sE := &TODO{Number: 11, Task: "Task2"}
	todoArr[0] = fE
	todoArr[1] = sE
}

> cannot use fE (type *TODO) as Type TODO in assignment

i don't know why
also i want to know if there is a short form to declare and initialize array/slice in golang like this

[]TODO{&TODO{Number: 10, Task: "Task1"}, &TODO{Number: 11, Task: "Task2"}}

答案1

得分: 1

将代码更改为声明一个指向TODO的指针数组:

var todoArr [2]*TODO

fE := &TODO{Number: 10, Task: "Task1"}
sE := &TODO{Number: 11, Task: "Task2"}
todoArr[0] = fE
todoArr[1] = sE

或者将TODO值放入数组中的代码更改为:

var todoArr [2]TODO

fE := TODO{Number: 10, Task: "Task1"}
sE := TODO{Number: 11, Task: "Task2"}
todoArr[0] = fE
todoArr[1] = sE

您可以使用文字语法声明一个切片,如下所示:

[]*TODO{&TODO{Number: 10, Task: "Task1"}, &TODO{Number: 11, Task: "Task2"}}

或者

[]TODO{TODO{Number: 10, Task: "Task1"}, TODO{Number: 11, Task: "Task2"}}

根据您是否选择使用指针来决定。

英文:

Change the code to declare an array of pointer to TODO:

var todoArr [2]*TODO

fE := &TODO{Number: 10, Task: "Task1"}
sE := &TODO{Number: 11, Task: "Task2"}
todoArr[0] = fE
todoArr[1] = sE

or change the code to put TODO values in the array:

var todoArr [2]TODO

fE := TODO{Number: 10, Task: "Task1"}
sE := TODO{Number: 11, Task: "Task2"}
todoArr[0] = fE
todoArr[1] = sE

You can declare a slice using literal syntax as

[]*TODO{&TODO{Number: 10, Task: "Task1"}, &TODO{Number: 11, Task: "Task2"}}

or

[]TODO{TODO{Number: 10, Task: "Task1"}, TODO{Number: 11, Task: "Task2"}}

depending on your choice of using pointers or not.

huangapple
  • 本文由 发表于 2017年4月13日 04:49:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/43379394.html
匿名

发表评论

匿名网友

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

确定