16

If I have a custom type that simply redefines a pre-defined type with a name:

type Answer string

And I try to use it in a function that accepts the pre-defined type:

func acceptMe(str string) {
    fmt.Println(str)
}

func main() {
    type Answer string
    var ans Answer = "hello"

    // cannot use ans (type Answer) as type string in function argument
    acceptMe(ans)          
    // invalid type assertion: ans.(string) (non-interface type Answer on left)
    acceptMe(ans.(string)) 
    // Does work, but I don't understand why if the previous doesn't:
    acceptMe(string(ans))
}

Why does the type assertion fail, but the conversion work?

atp
  • 30,132
  • 47
  • 125
  • 187

1 Answers1

22

Type assertion works for interfaces only. Interface can have arbitrary underlying type, so we have type assertion and type switch to the rescue. Type assertion returns bool as the second return value to indicate if assertion was successful.

Your custom type Answer can have only one underlying type. You already know the exact type - Answer and the underlying type - string. You don't need assertions, since conversion to the underlying type will always be successful.

Old answer:

Just convert your custom type to string. The conversion will succeed since your custom type has string as an underlying type. The conversion syntax: string(ans). Go Play

Michael Lihs
  • 7,460
  • 17
  • 52
  • 85
Kluyg
  • 5,119
  • 2
  • 25
  • 28
  • Thanks, while you were answering the question I discovered this, too. I'd like to know why that is the case. – atp Sep 09 '13 at 05:37
  • Ups :) Updated the answer. > // Does work, but I don't understand why if the previous doesn't. Type assertion and type conversion are orthogonal things. Type assertion is for interfaces only. – Kluyg Sep 09 '13 at 06:05