Convert a string fragment to a custom type fragment

I'm new to Go, so that 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)
}

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

From the specifications, it looks like the [] string is not the same basic type as the [] Card, so type conversion cannot happen.

Is this really the case, or am I missing something?

If so, why is it so? Assuming that in a non-pet program, I have an input fragment of a line, is there a way to “drop” it into a piece of the map, or do I need to create a new structure and copy the data into it? (Which I would like to avoid, since the functions that I will need to call will change the contents of the slice).

+4
3

Card , string ( : string), []Card []string (, , Hand).

T1 T2, , , T1 T2, . ? ( ). , []byte 1 . []int32 4 . , , 0..255.

: Card s, string ? Card, string (, , string). , []Card, []Card , :

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

, Card string, , string. string string, , :

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

[]string, []Card. " " . toCards(), , .

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

:

:

[] [] {} golang

[] [] {}

, [] T [] Go?

+7

, , (, []string []Card), . , , .

- . ( ) unsafe:

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

:

unsafe.Pointer . .

2011 2016 , " ".

+2

, [] , [] Card, .

. , string Card .

If so, why is it so? Assuming that in a non-pet program, I have an input fragment of a line, is there a way to “drop” it into a piece of the map, or do I need to create a new structure and copy the data into it? (Which I would like to avoid, since the functions that I will need to call will change the contents of the slice).

Since conversions are always explicit, and designers believe that copy is implied in conversions, it should also be explicit.

+1
source

All Articles