英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论