Is it possible to convert []A to []B, or []*A to []*B ?

210 views
Skip to first unread message

nicolas...@gmail.com

unread,
Jun 26, 2014, 11:59:53 AM6/26/14
to golan...@googlegroups.com
Having "type A int" and "type B A", I try to convert []A to []B, but it fails.

It seems that Go doesn't allow such conversion, notwithstanding the memory layout is the same for []A and []B ?

So, I must convert each element to the target type into a new slice, as in the two following snippets ?

Conversion []A to []B:
http://play.golang.org/p/BXHg66NKUs

Conversion []*A to []*B:
http://play.golang.org/p/jUoOirBybN


Brad Fitzpatrick

unread,
Jun 26, 2014, 12:11:30 PM6/26/14
to nicolas...@gmail.com, golang-nuts


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Erwin

unread,
Jun 26, 2014, 2:43:08 PM6/26/14
to nicolas...@gmail.com, golang-nuts
it can be done using unsafe.Pointer, see

http://play.golang.org/p/PbhbnlTN_v


chris dollin

unread,
Jun 26, 2014, 2:55:46 PM6/26/14
to Erwin, nicolas...@gmail.com, golang-nuts
On 26 June 2014 19:42, Erwin <snes...@gmail.com> wrote:
it can be done using unsafe.Pointer, see

http://play.golang.org/p/PbhbnlTN_v

You can also keep warm by setting fire to the carpet.

Using unsafe to do a type conversions is an open opportunity
for error.

One suspects that there as an earlier design decision leading
the code up the garden path.

Chris

--
Chris "allusive" Dollin

Erwin

unread,
Jun 26, 2014, 2:56:37 PM6/26/14
to chris dollin, nicolas...@gmail.com, golang-nuts
Surely caution is needed, but here it is actually safe to do so. 

Jesse McNelis

unread,
Jun 26, 2014, 7:09:56 PM6/26/14
to Erwin, chris dollin, nicolas riesch, golang-nuts
On Fri, Jun 27, 2014 at 4:56 AM, Erwin <snes...@gmail.com> wrote:
> Surely caution is needed, but here it is actually safe to do so.

As long as everyone that works on this code knows that A and B need to
always be the same size and that you need to be careful with what you
assign to the variable 'b' and that the size of slices doesn't change
in a type specific way sometime in the future or on some different
implementation.

I'm sure the newbie asking this question knows all of this.

chai2010

unread,
Jun 26, 2014, 9:01:17 PM6/26/14
to Jesse McNelis, Erwin, chris dollin, nicolas riesch, golang-nuts
This is a example:

convert []A to []B:
b := Slice([]A{1,2}, reflect.TypeOf([]B(nil))).([]B)

And sizeof(A) and sizeof(B) don't need the same size.




--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages