5

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 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Hi Ben, Thanks for the response. Yes, directly use &publish.Book{...} works. But I'm wondering why I cannot make a local instance: var reading publish.Book, and then &reading{...} ??
var reading publish.Book declares a variable of Book, it doesn't create an alias of that type. If you want you can assign to the elements of reading using reading.Name = "Learn Go Lang" etc...
what does "a variable of Book" mean? if it does not equivalent to alias or instance of that type?
alias and instance are not equivalent. An Alias is a renaming of a type. You can have multiple instances of the same type. (I meant a variable of type book).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.