[]int to string conversion

4,558 views
Skip to first unread message

Sergei Skorobogatov

unread,
Jul 1, 2010, 3:12:28 AM7/1/10
to golang-nuts
It seems, that []int to string conversion has changed
in compiler. Earlier, having type

Ints []int

I could convert the value x of type Ints to string by
direct conversion:

string(x)

Now I have to apply two conversions:

string(([]int)(x))

The language specification says nothing about
conversion of named array types to string.
Though, I think, if the underlying type of named type
is []int, it would be reasonable to allow to convert
values of this named type to string.

bflm

unread,
Jul 1, 2010, 5:04:04 AM7/1/10
to golang-nuts
On Jul 1, 9:12 am, Sergei Skorobogatov <skor...@rambler.ru> wrote:
> It seems, that []int to string conversion has changed
> in compiler. Earlier, having type
>
>         Ints []int
>
> I could convert the value x of type Ints to string by
> direct conversion:
>
>         string(x)
>
> Now I have to apply two conversions:
>
>         string(([]int)(x))
>
> The language specification says nothing about
> conversion of named array types to string.

IMO it does. Looking at:

http://golang.org/doc/go_spec.html#Conversions

[quote]
3. Converting a value of type []int to a string type yields a string
that is the concatenation of the individual integers converted to
strings.
[/quote]

it folows that if 'x' is type []int it (conversion to string) should
work. But if 'x' is of type 'Ints' (i.e. *not* []int as required by
specs), it should not.

> Though, I think, if the underlying type of named type
> is []int, it would be reasonable to allow to convert
> values of this named type to string.

IMO it wouldn't be reasonable, because that equals implicit conversion
(Ints -> []int) and that's consistently not allowed in Go anywhere.

Russ Cox

unread,
Jul 1, 2010, 1:21:58 PM7/1/10
to Sergei Skorobogatov, golang-nuts
On Thu, Jul 1, 2010 at 00:12, Sergei Skorobogatov <sko...@rambler.ru> wrote:
> It seems, that []int to string conversion has changed
> in compiler. Earlier, having type
>
>        Ints []int
>
> I could convert the value x of type Ints to string by
> direct conversion:
>
>        string(x)
>
> Now I have to apply two conversions:
>
>        string(([]int)(x))

Yes, this changed. When we updated the conversion rules
I rewrote that part of the type checker and got a lot of things
right (== matching the spec) that weren't right before.
This is one of them.

You don't need the parens, by the way: string([]int(x)) is fine.

I don't remember whether we explicitly intended to disallow
string(x) in this case, but the spec's wording is precise: it
refers to []int and []byte for that side of the conversion and
"a string type" or "an integer type" for the other side.

Feel free to file an issue about this to remind us to revisit
the question.

Russ

Reply all
Reply to author
Forward
0 new messages