Implicit cast of string vs. []byte

124 views
Skip to first unread message

Ivan Bertona

unread,
Jun 24, 2017, 8:16:23 PM6/24/17
to golang-nuts
Hello,

When I try to compile this piece of code:

package main

type MyString string
type MyBytes []byte

func GetString() (string, error) {
return "", nil
}

func GetBytes() ([]byte, error) {
return nil, nil
}

func main() {
var s MyString
var b MyBytes
var err error

s, err = GetString()
b, err = GetBytes()
}

I get this error: tmp/sandbox008752331/main.go:19: cannot assign string to s (type MyString) in multiple assignment 

Does anyone know why implicit casting from []byte to MyBytes works, but it doesn't for string to MyString?

Best,
Ivan

Ayan George

unread,
Jun 24, 2017, 8:46:55 PM6/24/17
to golan...@googlegroups.com

On 06/24/2017 08:16 PM, Ivan Bertona wrote:
> Hello,
>
> When I try to compile this piece of code:
>

I think it violates the second assignability rule since both 'string'
and MyString are named types. string happens to be a a pre-declared
named type:

https://golang.org/ref/spec#Assignability

Whereas []byte is unnamed therefore at least one of the types in the
expression is unnamed.

Here are a couple of relevant blog posts about it:

https://medium.com/learning-the-go-programming-language
http://www.laktek.com/2012/01/27/learning-go-types/

Someone please correct me if I'm wrong.

-ayan

Ivan Bertona

unread,
Jun 24, 2017, 8:56:06 PM6/24/17
to golang-nuts
I see, thank you!

Stefan Nilsson

unread,
Jun 25, 2017, 2:11:08 AM6/25/17
to golang-nuts
This may not be what you want, but starting from Go 1.9 it's possible to declare a type alias using the syntax

type MyString = string

As opposed to a type definition, an alias declaration doesn't create a new distinct type different from the type it's created from. Type aliases are not meant to be an everyday feature of Go, but are intended to be used during large and complex code refactoring.
Reply all
Reply to author
Forward
0 new messages