-2

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

  • 1
    The difference is that "foo" is an **untyped** constant value which can take the type of Foo, and bar is a **typed** variable, a variable of type string and it cannot automatically take the type string, only via explicit type conversion. – icza May 27 '22 at 13:22

2 Answers2

1

The last one doesn't work because Go has strong type check; also if Foo has string as base type, it's not a string.

For that reason you cannot assign a string to it.

to achieve what you want you have to do casting

func main() {
    var a = "hello"
    var b Foo
    b = Foo(a)
    fmt.Println("b:", b)
}
Massimo Costa
  • 1,864
  • 15
  • 23
1

Let me correct this

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

or just

var foo = Foo(bar)
vuho.hoho
  • 61
  • 3