Initializing custom type


Can someone help me to understand the following situation?

Having a custom type

type Foo string

This construction works:

var foo Foo = "foo"
fmt.Printf("\n%s", foo)

And this:

var bar = "bar"
var foo Foo = bar
fmt.Printf("\n%s", foo)

Throws a cannot use bar (variable of type string) as type Foo in variable declaration. What are the differences and how can I initialize this type properly?
Thanks 🙂


Let me correct this

var bar = "bar"
var foo Foo = Foo(bar)
fmt.Printf("\n%s", foo)

or just

var foo = Foo(bar)

Answered By – vuho.hoho

Answer Checked By – Senaida (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.