简体   繁体   中英

Converting Slice pointer to Slice in go

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM