Ask Your Question
0

How can a pointer to a slice of a certain type be converted to a slice of a different type?

asked 2023-05-10 03:17:16 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-10 03:37:01 +0000

david gravatar image

It is not possible to directly convert a pointer to a slice of one type to a slice of a different type. However, you can manually copy the data from the original slice to a new slice of a different type using a loop or a built-in function like copy(). Here's an example:

// create a slice of integers
ints := []int{1, 2, 3, 4, 5}

// create a pointer to the slice of integers
intPtr := &ints

// create a new slice of float64s with the same length as the original slice
floats := make([]float64, len(*intPtr))

// manually copy the data from the original slice to the new slice
for i, v := range *intPtr {
    floats[i] = float64(v)
}

// prints [1 2 3 4 5] followed by [1 2 3 4 5] as float64s
fmt.Println(ints)
fmt.Println(floats)
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-10 03:17:16 +0000

Seen: 20 times

Last updated: May 10 '23