import struct in go, get "not a type" error

huangapple go评论68阅读模式
英文:

import struct in go, get "not a type" error

问题

我导入了另一个包中定义的结构体,在尝试使用它来构造一个字面量时,出现了“不是类型”的错误。

在publish.go中:

type Book struct {
    Name      string
    Author    string
    Published bool
}

在store.go中:

import "publish"

func Init() {
    var reading publish.Book

    b := &reading{
        Name:      "Learn Go Lang",
        Author:    "Rob",
        Published: true,
    }
}

错误信息:reading不是一个类型。

英文:

I import a struct defined in another package, when try to use it to construct a literal, get a "not a type" error.

In publish.go

type Book struct {
    Name string
    Author string
    Published bool
}

In store.go

import "publish"

func Init() {
    var reading publish.Book

    b := &reading {
        Name: "Learn Go Lang",
        Author: "Rob",
        Published: true
    }
}

Error: reading is not a type

答案1

得分: 4

这里你试图创建一个类型为"reading"的结构体:

b := &reading{
       Name: "Learn Go Lang",
       Author: "Rob",
       Published: true
    }

你想要的是一个类型为publish.Book的结构体:

b := &publish.Book{
       Name: "Learn Go Lang",
       Author: "Rob",
       Published: true,
    }

另外,在多行结构体声明的最后一个字段后面也需要加上逗号。

英文:

Here you try to make a struct of Type "reading"

b := &reading {
       Name: "Learn Go Lang",
       Author: "Rob",
       Published: true
    }

What you want is a struct of type publish.Book

b := & publish.Book {
       Name: "Learn Go Lang",
       Author: "Rob",
       Published: true,
    }

plus you also need a comma at the end of the last in a multi-line struct declaration.

huangapple
  • 本文由 发表于 2017年3月16日 06:30:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/42821934.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定