简体   繁体   English

在golang中初始化结构类型的空数组

[英]Initializing an empty array of struct type in golang

I have initialized a struct :我已经初始化了一个结构:

type DayAndTime struct {
    days string
    time string
  }

I have initialized an empty set of array of this DayAndTime type:我已经初始化了这个DayAndTime类型的空数组集:

day := []DayAndTime{}

And put a value in it: day[0] = DayAndTime{"Monday", "8.00 PM"}并在其中输入一个值: day[0] = DayAndTime{"Monday", "8.00 PM"}

But it shows a runtime error:但它显示了一个运行时错误:

panic: runtime error: invalid memory address or nil pointer dereference

Why is this happenning and what could be a possible solution?为什么会发生这种情况,可能的解决方案是什么?

edit: It's actually a slice not an array.编辑:它实际上是一个切片而不是一个数组。

Here you have a zero-length slice, the len and cap functions will both return 0 for a zero-valued slice这里你有一个零长度的切片, lencap函数都将为零值切片返回 0

A slice cannot be grown beyond its capacity.切片不能超出其容量增长。 Attempting to do so will cause a runtime panic, just as when indexing outside the bounds of a slice or array.尝试这样做会导致运行时恐慌,就像在切片或数组的边界之外进行索引时一样。 Similarly, slices cannot be re-sliced below zero to access earlier elements in the array.同样,切片不能在零以下重新切片以访问数组中较早的元素。

You may us make to initialize the slice with capacity and assign with index or use append to add values to slice您可以使用容量初始化切片并使用索引分配或使用附加向切片添加值

Both are valid code两者都是有效代码

var day []DayAndTime
day = append(day, DayAndTime{"Monday", "8.00 PM"})

or

var day = make([]DayAndTime, 1)
day[0] = DayAndTime{"Monday", "8.00 PM"}

Using append is recomended推荐使用 append

Here is a sample code justifying/explaining the answer https://play.golang.org/p/ajsli-6Vqw这是一个证明/解释答案的示例代码https://play.golang.org/p/ajsli-6Vqw

package main

import (
    "fmt"
)

type DayAndTime struct {
    days string
    time string
}

func ZeroLength() {
    var day = []DayAndTime{}
    fmt.Println("Hello, playground", cap(day), len(day), day)
}

func AppendArray() {
    var day = []DayAndTime{}
    day = append(day, DayAndTime{"Monday", "8.00 PM"})
    fmt.Println("Hello, playground", cap(day), len(day), day)
}

func SetIndex() {
    var day = make([]DayAndTime, 1)
    day[0] = DayAndTime{"Monday", "8.00 PM"}
    fmt.Println("Hello, playground", cap(day), len(day), day)
}

func main() {
    ZeroLength()
    AppendArray()
    SetIndex()
}

If you print the length of day , you will get 0 , so you cannot access day[0] , which does not exist.如果您打印day的长度,您将获得0 ,因此您无法访问不存在的day[0]

You can write it in this way: day = append(day, DayAndTime{"Monday", "8.00 PM"})你可以这样写: day = append(day, DayAndTime{"Monday", "8.00 PM"})

This should be the right syntax in your example:在您的示例中,这应该是正确的语法:

type DayAndTime struct {
    days string
    time string
}

days := []*DayAndTime{}

You asked for a solution for arrays, but in your code you show a slice.您要求为数组提供解决方案,但在您的代码中显示了一个切片。

foo := []string{}
t := reflect.TypeOf(foo)
fmt.Println(t.Kind()) // slice

bar := [2]string{}
tt := reflect.TypeOf(bar)
fmt.Println(tt.Kind()) // array

Anyway, ... you got that error because days[0] is out of range in the slice.无论如何,......你得到了那个错误,因为 days[0] 超出了切片的范围。 Thant actually contains zero item and its length is zero. Thant 实际上包含零个项目,其长度为零。 You have to use append, that return new slice, and then you can access to days[0].您必须使用 append,返回新切片,然后才能访问 days[0]。 Or can initialize with make.或者可以用make初始化。

package main

import "fmt"

type DayAndTime struct {
    days string
    time string
}

func main() {
    days := []DayAndTime{}
    days = append(days, DayAndTime{"days ...", "time ..."})
    fmt.Printf("%v", days[0].days)
}

Another solution is to build an array instead of slice另一种解决方案是构建一个数组而不是切片

func main() {
    days := [2]DayAndTime{}
    days[0].days = "fooo"
    fmt.Printf("%v", days[0].days)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM