Golang 使用类型结构列表

问题描述

我想像 List 一样使用我的 Struct,但 IDE 没有机会使用。 我知道,有语法问题,但我找不到真正的语法。

我不知道我的代码错误在哪里。

使用结构列表时正确的语法是什么?

package main

import (
    "encoding/json"
    "fmt"
)

type Student struct {
    Firstname string   `json:"firstname"`
    Lastname  string   `json:"lastname"`
    Email     string   `json:"email"`
    Languages []string `json:"languages"`
    Profile   []Profile
}

type Profile struct {
    Username  string            `json:"username"`
    Followers int               `json:"followers"`
    Grades    map[string]string `json:"grades"`
}

func main() {

    var John Student

    // defining struct

    John = Student{
        Firstname: "John",Lastname:  "Miller",Email:     "johnmiller@gmail.com",Profile: Profile{
            {
                Username:  "Miller_267",Followers: 1988,Grades:    map[string]string{"Education Level": "master","University": ""},},{
                Username:  "John Miller",Followers: 1997,"University": "Leicsheter University"},Languages: []string{"Eng","Esp"},}

    res,err := json.MarshalIndent(John,""," ")
    if err != nil {
        panic(err)
    }

    fmt.Println(string(res),"\n",err)
}

在上面的语法中,我的错误是什么?

解决方法

您需要在文字中使用切片,以匹配类型定义:

package main

import (
   "encoding/json"
   "os"
)

type profile struct {
   Followers int
   Username string
}

type student struct {
   Firstname string
   Profile []profile
}

func main() {
   john := student{
      Profile: []profile{
         {1988,"Miller_267"},{1997,"John Miller"},},}
   json.NewEncoder(os.Stdout).Encode(john)
}