猿问

如何比较 Golang 中的结构数据和接口数据?

我正在尝试在 Golang 中创建一个通用的二叉树。如何比较来自接口的数据和代码中的输入数据?这是我正在尝试做的一个例子。给我带来麻烦的比较是这个


 } else if cur.data < data {

-


package DSAA


type TreeNode struct {

    data interface{}

    right *TreeNode

    left *TreeNode

}


type BinarySearchTree struct {

    root *TreeNode

}


func BSTCreate() *BinarySearchTree {

    return &BinarySearchTree{nil}

}


func (b *BinarySearchTree) Insert(cur TreeNode, data interface{}) *BinarySearchTree {

    if &cur == nil {

        cur := &TreeNode{data, nil, nil}

    } else if cur.data < data {

        b = b.Insert(*cur.left, data)

    } else {

        b = b.Insert(*cur.right, data)

    }

    return b

}


尚方宝剑之说
浏览 131回答 1
1回答

偶然的你

您有一些选择:1- 使用运行时类型开关:package mainimport (&nbsp; &nbsp; "fmt")func main() {&nbsp; &nbsp; fmt.Println(Less(1, 2))&nbsp; &nbsp; &nbsp; &nbsp;// true&nbsp; &nbsp; fmt.Println(Less("AB", "AC")) // true}func Less(a, b interface{}) bool {&nbsp; &nbsp; switch v := a.(type) {&nbsp; &nbsp; case int:&nbsp; &nbsp; &nbsp; &nbsp; w := b.(int)&nbsp; &nbsp; &nbsp; &nbsp; return v < w&nbsp; &nbsp; case string:&nbsp; &nbsp; &nbsp; &nbsp; w := b.(string)&nbsp; &nbsp; &nbsp; &nbsp; return v < w&nbsp; &nbsp; }&nbsp; &nbsp; return false}然后替换} else if cur.data < data {为 } else if Less(cur.data , data) {2-使用Comparer interface:package mainimport (&nbsp; &nbsp; "fmt")type Comparer interface {&nbsp; &nbsp; // Less reports whether the element&nbsp; is less than b&nbsp; &nbsp; Less(b interface{}) bool}func main() {&nbsp; &nbsp; a, b := Int(1), Int(2)&nbsp; &nbsp; fmt.Println(a.Less(b)) // true&nbsp; &nbsp; c, d := St("A"), St("B")&nbsp; &nbsp; fmt.Println(c.Less(d)) // true}type Int intfunc (t Int) Less(b interface{}) bool {&nbsp; &nbsp; if v, ok := b.(Int); ok {&nbsp; &nbsp; &nbsp; &nbsp; return int(t) < int(v)&nbsp; &nbsp; }&nbsp; &nbsp; return false}type St stringfunc (t St) Less(b interface{}) bool {&nbsp; &nbsp; if v, ok := b.(St); ok {&nbsp; &nbsp; &nbsp; &nbsp; return string(t) < string(v)&nbsp; &nbsp; }&nbsp; &nbsp; return false}3-使用reflect
随时随地看视频慕课网APP

相关分类

Go
我要回答