duanchun2349 2014-08-03 15:47
浏览 25
已采纳

一片类型结构访问索引超出范围

I am trying to use slice of type struct. Look at the following sample

package main

import (
    "fmt"
)

func main() {

    arr := []struct {
        A string
        B string
    } {}

    arr[0].A = "I am"
    arr[0].B = "First"

    arr[1].A = "I am"
    arr[1].B = "Second"

    fmt.Println(arr)

}

When I compile this code I've got out of range error. Why?

  • 写回答

2条回答 默认 最新

  • dongtaoxue4674 2014-08-03 15:56
    关注

    You need to append new elements to your slice (if you don't make an array as in FUZxxl's answer.
    It is easier with a named type instead of a type literal.

    See "Appending to and copying slices" and "Arrays, slices (and strings): The mechanics of 'append'".

    Example <kbd>play.golang.org</kbd>

    package main
    
    import (
        "fmt"
    )
    
    func main() {
    
        type T struct {
            A string
            B string
        }
    
        arr := []T{}
    
        arr = append(arr, T{A: "I am", B: "First"})
        arr = append(arr, T{A: "I am", B: "Second"})
    
        fmt.Println(arr)
    }
    

    Output:

    [{I am First} {I am Second}]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度