0

I have methods which returns the data in slice pointer, now i have to convert it into slice array. how to convert slice pointer to slice array.

peerRoundState, err := s.nodeview.PeerRoundStates()
fmt.Println("This return value is slice pointer", peerRoundState)
if err != nil {
    return nil, err
}
//PeerRoundStates this is type of slice.
return &ConsensusResponse{
    RoundState: s.nodeview.RoundState().RoundStateSimple(),
    PeerRoundStates: peerRound,
}, nil

i want to convert peerRoundState type of slice pointer to PeerRoundStates slice array.

Nagaraj M
  • 387
  • 1
  • 5
  • 16
  • 3
    You cannot "convert" slice pointers to slices, but you can trivially dereference them with [the `*` operator](https://golang.org/ref/spec#Address_operators). That being said, there are no slices in this piece of code, so it's unclear what you're asking. – Peter Oct 26 '18 at 09:26
  • Please consider taking the [Tour of Go](https://tour.golang.org), as it covers the Go basics and terminology pretty well and only takes a few minutes. I think there may be some confusion in terminology here - as Peter noted, there are no apparent slices or slice pointers in the quoted code, and "convert slice pointer to slice array" doesn't really make sense - e.g. a conversion from `*[]int` to `[3][]int` would not be possible nor desirable. – Adrian Oct 26 '18 at 13:25

1 Answers1

3

For slice, you have to be carefully about using value slice instead of pointer val := *ptr, because both will point to the same data array address. Changes done in slice pointer, will reflect on value slice as well, because slice data structure contains references actual data array.

Check playground example for 2 cases of assignment from pointer to value. Here is described two cases:

  1. copying slice as a value - which copies the slice properties and address to the data array
  2. copying slice elements - which copies all slice elements and creates a new slice
Maxian Nicu
  • 2,166
  • 3
  • 17
  • 31