[英]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但是如果我将
mytype
更改为int
它将起作用
// []int It works
var slice = []int{11, 22, 33, 44}
The error says panic: interface conversion: interface {} is *[]main.mytype, not *[]int
错误说
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
.因为我将
sliceType
声明为int
。 I still don't know how to make a dynamic type in Golang.我仍然不知道如何在Golang中制作动态类型。
Any help will be appreciate.任何帮助将不胜感激。 Here's the Golang Playground of my code https://play.golang.org/p/5QyTMcZFGPi
这是我的代码的 Golang Playground https://play.golang.org/p/5QyTMcZFGPi
So go doesn't let you do dynamic types like that.所以 go 不允许你做这样的动态类型。 So if you want your code to work with
mytype
, try this:因此,如果您希望您的代码与
mytype
一起mytype
,请尝试以下操作:
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 .查看sort.Reverse 。
The sort package offers an interesting pattern that many gophers use to get around the lack of generics/templates in go. sort 包提供了一个有趣的模式,许多 gopher 使用它来解决 go 中缺少泛型/模板的问题。 The tl;dr of the pattern is to use interfaces and add methods to those interfaces to modify the underlying data.
该模式的 tl;dr 是使用接口并向这些接口添加方法来修改底层数据。 That way each implementation of the interface knows the type, but the receiving method doesn't have to care.
这样接口的每个实现都知道类型,但接收方法不必关心。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.