You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go语言中map使用string[][]时遇复合字面量缺少类型错误求助

解决Go中"missing type in composite literal"错误

嘿,我来帮你搞定这个问题!你遇到的missing type in composite literal错误,是因为在初始化结构体的name字段时,没有明确指定复合字面量的类型——虽然name字段已经定义为[][]string,但Go编译器需要你在复合字面量里明确外层切片的类型,才能正确解析。

修正后的代码

package main
import ( "fmt" )
type person struct { 
    name [][]string 
}
func main() {
    var people = map[string]*person{}
    // 显式指定外层切片类型,让编译器正确识别复合字面量
    people["first person"] = &person{name: [][]string{{"My name","30"}}}
    // 访问name字段才能输出目标二维切片内容,而非打印指针
    fmt.Println(people["first person"].name)
}

关键说明

  1. 复合字面量类型明确:name是[][]string(字符串切片的切片),初始化时必须用[][]string{{...}}来告知编译器外层切片的类型,否则编译器无法推断结构,就会抛出错误。
  2. 输出目标内容:原代码打印的是*person指针,输出会是&{[[My name 30]]}这类格式。要得到你期望的[[My name 30]],需要访问指针指向的结构体的name字段。

运行修正后的代码,就能得到你想要的输出结果啦!

内容的提问来源于stack exchange,提问作者nagulan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:23:45