19

I'm quite new to Go, so this might be obvious. The compiler does not allow the following code: (http://play.golang.org/p/3sTLguUG3l)

package main

import "fmt"

type Card string
type Hand []Card

func NewHand(cards []Card) Hand {
    hand := Hand(cards)
    return hand
}

func main() {
    value := []string{"a", "b", "c"}
    firstHand := NewHand(value)
    fmt.Println(firstHand)
}

The error is: /tmp/sandbox089372356/main.go:15: cannot use value (type []string) as type []Card in argument to NewHand

From the specs, it looks like []string is not the same underlying type as []Card, so the type conversion cannot occur.

Is it, indeed, the case, or did I miss something?

If it is the case, why is it so? Assuming, in a non-pet-example program, I have as input a slice of string, is there any way to "cast" it into a slice of Card, or do I have to create a new structure and copy the data into it? (Which I'd like to avoid since the functions I'll need to call will modify the slice content).

Frédéric Donckels
  • 633
  • 1
  • 6
  • 21
  • 2
    By `type Card string` you are introducing an actual new type, not a type alias. `Card` is a new type which can have it's set of methods and behavior. – Kaveh Shahbazian Mar 13 '15 at 12:36

3 Answers3

26

There is no technical reason why conversion between slices whose elements have identical underlying types (such as []string and []Card) is forbidden. It was a specification decision to help avoid accidental conversions between unrelated types that by chance have the same structure.

The safe solution is to copy the slice. However, it is possible to convert directly (without copying) using the unsafe package:

value := []string{"a", "b", "c"}
// convert &value (type *[]string) to *[]Card via unsafe.Pointer, then deref
cards := *(*[]Card)(unsafe.Pointer(&value))
firstHand := NewHand(cards)

https://play.golang.org/p/tto57DERjYa

Obligatory warning from the package documentation:

unsafe.Pointer allows a program to defeat the type system and read and write arbitrary memory. It should be used with extreme care.

There was a discussion on the mailing list about conversions and underlying types in 2011, and a proposal to allow conversion between recursively equivalent types in 2016 which was declined "until there is a more compelling reason".

tom
  • 21,844
  • 6
  • 43
  • 36
15

The underlying type of Card might be the same as the underlying type of string (which is itself: string), but the underlying type of []Card is not the same as the underlying type of []string (and therefore the same applies to Hand).

You cannot convert a slice of T1 to a slice of T2, it's not a matter of what underlying types they have, if T1 is not identical to T2, you just can't. Why? Because slices of different element types may have different memory layout (different size in memory). For example the elements of type []byte occupy 1 byte each. The elements of []int32 occupy 4 bytes each. Obviously you can't just convert one to the other even if all values are in the range 0..255.

But back to the roots: if you need a slice of Cards, why do you create a slice of strings in the first place? You created the type Card because it is not a string (or at least not just a string). If so and you require []Card, then create []Card in the first place and all your problems go away:

value := []Card{"a", "b", "c"}
firstHand := NewHand(value)
fmt.Println(firstHand)

Note that you are still able to initialize the slice of Card with untyped constant string literals because it can be used to initialize any type whose underlying type is string. If you want to involve typed string constants or non-constant expressions of type string, you need explicit conversion, like in the example below:

s := "ddd"
value := []Card{"a", "b", "c", Card(s)}

If you have a []string, you need to manually build a []Card from it. There is no "easier" way. You can create a helper toCards() function so you can use it everywhere you need it.

func toCards(s []string) []Card {
    c := make([]Card, len(s))
    for i, v := range s {
        c[i] = Card(v)
    }
    return c
}

Some links for background and reasoning:

Go Language Specification: Conversions

why []string can not be converted to []interface{} in golang

Cannot convert []string to []interface {}

What about memory layout means that []T cannot be converted to []interface in Go?

Community
  • 1
  • 1
icza
  • 389,944
  • 63
  • 907
  • 827
  • as I mentioned, this is a pet example, in my real setup, the `[]string` comes from an external source on which I have no control. – Frédéric Donckels Mar 13 '15 at 13:08
  • @FDO Yes, I know, but if this is a pet example, in more complex examples there is even more reason to create proper types in the first place. Look at it as in this example you don't have the required input slice, just some data from which you can produce the required input slice. – icza Mar 13 '15 at 13:11
  • 1
    I'm not sure what you mean by this. The output of `strings.Split`, for instance, is a `[]string`. I created the type `Card` and `Hand` because I want 'methods' for those types, and the output of `strings.Split` is used as input for those types and it seems a waste of time/cpu/code to just copy input in a new data structure. Why would `[]string` and `[]Card` have a different memory layout ? (the `[]int32` and `[]byte` example is obvious, but in my case, it's not so obvious to me) – Frédéric Donckels Mar 13 '15 at 13:19
  • 1
    @FDO If you have a `[]string`, you need to manually build a `[]Card` from it. There is no "easier" way. You can create a helper `toCards()` function so you can use it everywhere you need it. – icza Mar 13 '15 at 13:43
  • Ok. Thank you. I'm still trying to figure out the rationale behind this design choice, so if you have any article I could read, I'd be very grateful. – Frédéric Donckels Mar 13 '15 at 13:55
  • @FDO Added some links. Some are more general and targets `[]interface{}` but some reasoning mentioned there applies here too. – icza Mar 13 '15 at 14:10
  • Since Golang 1.18 this can be done `func StringSliceToCustomStringSlice[T ~string](s []string) []T` – jesusnoseq Oct 28 '22 at 14:39
1

From the specs, it looks like []string is not the same underlying type as []Card, so the type conversion cannot occur.

Exactly right. You have to convert it by looping and copying over each element, converting the type from string to Card on the way.

If it is the case, why is it so? Assuming, in a non-pet-example program, I have as input a slice of string, is there any way to "cast" it into a slice of Card, or do I have to create a new structure and copy the data into it? (Which I'd like to avoid since the functions I'll need to call will modify the slice content).

Because conversions are always explicit and the designers felt that when a conversion implicitly involves a copy it should be made explicit as well.

nemo
  • 55,207
  • 13
  • 135
  • 135
  • 1
    Still, I don't understand why a copy is needed (isn't there any way to avoid it?). There's still a missing connection in my understanding. – Frédéric Donckels Mar 13 '15 at 11:51
  • @FDO, it's a copy because everything is go is a value. There's no way to make a variable, and assign a value without copying something, even if it's just a pointer. – JimB Mar 13 '15 at 12:55