FAQ
The following program displays unexpected behavior (at least to me) when
the // send[3] = new(Thing) line is commented in or out:

package main

import (
"fmt"
"encoding/gob"
"bytes"
)

type Thing struct {
Number int32
}

func (t Thing) String() string {
return fmt.Sprintf("%d", t.Number)
}

func main() {
var network bytes.Buffer
enc := gob.NewEncoder(&network)
dec := gob.NewDecoder(&network)

send := make([]*Thing, 4)
send[0] = &Thing{Number: 1}
send[1] = &Thing{Number: 10}
send[2] = &Thing{Number: 11}
// send[3] = new(Thing)

enc.Encode(send)

var receive []*Thing
dec.Decode(&receive)
fmt.Printf("%s\n", receive)
}

When commented out this program outputs [] (i.e. there's nothing in the
received slice of *Thing). When commented in it outputs [1 10 11 0].

Is this expected behavior? (i.e. that the nil pointer in the sent slice
seems to kill the slice completely).

John.

--

Search Discussions

  • Cole Mickens at Jan 2, 2013 at 5:34 pm
    Check your errors: http://play.golang.org/p/tcrWAPGR7o
    On Wednesday, January 2, 2013 11:26:00 AM UTC-6, John Graham-Cumming wrote:

    The following program displays unexpected behavior (at least to me) when
    the // send[3] = new(Thing) line is commented in or out:

    package main

    import (
    "fmt"
    "encoding/gob"
    "bytes"
    )

    type Thing struct {
    Number int32
    }

    func (t Thing) String() string {
    return fmt.Sprintf("%d", t.Number)
    }

    func main() {
    var network bytes.Buffer
    enc := gob.NewEncoder(&network)
    dec := gob.NewDecoder(&network)

    send := make([]*Thing, 4)
    send[0] = &Thing{Number: 1}
    send[1] = &Thing{Number: 10}
    send[2] = &Thing{Number: 11}
    // send[3] = new(Thing)

    enc.Encode(send)

    var receive []*Thing
    dec.Decode(&receive)
    fmt.Printf("%s\n", receive)
    }

    When commented out this program outputs [] (i.e. there's nothing in the
    received slice of *Thing). When commented in it outputs [1 10 11 0].

    Is this expected behavior? (i.e. that the nil pointer in the sent slice
    seems to kill the slice completely).

    John.
    --
  • John Graham-Cumming at Jan 3, 2013 at 1:27 pm

    On Wednesday, January 2, 2013 5:34:29 PM UTC, Cole Mickens wrote:
    Check your errors: http://play.golang.org/p/tcrWAPGR7o

    Slaps self about the head.

    John.


    --

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-nuts @
categoriesgo
postedJan 2, '13 at 5:26p
activeJan 3, '13 at 1:27p
posts3
users2
websitegolang.org

People

Translate

site design / logo © 2021 Grokbase