简体   繁体   中英

How to assign dynamic types in slices

I made an app to reverse slice/array. I had a problem when make a slice with my own type. Here's will not work

type mytype int

func main() {
    // []mytype doesn't work
    // var slice = []mytype{11, 22, 33, 44}

But if I change mytype to int it will work

// []int It works
    var slice = []int{11, 22, 33, 44}

The error says panic: interface conversion: interface {} is *[]main.mytype, not *[]int

I figure out that the errors come from this line

sliceType := *slice.(*[]int)

Because I declaring the sliceType as int . I still don't know how to make a dynamic type in Golang.

Any help will be appreciate. Here's the Golang Playground of my code https://play.golang.org/p/5QyTMcZFGPi

So go doesn't let you do dynamic types like that. So if you want your code to work with mytype , try this:

package main

import (
    "fmt"
    "reflect"
)

//Reverse reverses a slice.
func Reverse(slice *[]mytype) {
    s := reflect.ValueOf(slice)

    if s.Kind() != reflect.Ptr {
        panic("Must be a pointer")
    }

    sliceLen := s.Elem().Len()
    sliceType := *slice
    for left, right := 0, sliceLen-1; left < right; left, right = left+1, right-1 {
        sliceType[left], sliceType[right] = sliceType[right], sliceType[left]
    }

    s.Elem().Set(reflect.ValueOf(sliceType))
}

type mytype int

func main() {
    var slice = []mytype{11, 22, 33, 44}

    Reverse(&slice)
    fmt.Println("RESULT", slice) // RESULT [44 33 22 11]
}

However, you might be thinking: "well I need to reverse lots of different types of slices...". Well go has you covered there as well!

Check out sort.Reverse .

The sort package offers an interesting pattern that many gophers use to get around the lack of generics/templates in go. The tl;dr of the pattern is to use interfaces and add methods to those interfaces to modify the underlying data. That way each implementation of the interface knows the type, but the receiving method doesn't have to care.

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