【问题标题】:How can I compare struct data and interface data in Golang?如何比较 Golang 中的结构数据和接口数据?
【发布时间】:2016-08-25 03:34:32
【问题描述】:

我正在尝试在 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
}

【问题讨论】:

标签: go data-structures


【解决方案1】:

您有一些选择:
1-使用运行时类型开关:

package main

import (
    "fmt"
)

func main() {
    fmt.Println(Less(1, 2))       // true
    fmt.Println(Less("AB", "AC")) // true
}

func Less(a, b interface{}) bool {
    switch v := a.(type) {
    case int:
        w := b.(int)
        return v < w
    case string:
        w := b.(string)
        return v < w

    }
    return false
}

然后将} else if cur.data &lt; data { 替换为 } else if Less(cur.data , data) {


2- 使用Comparer interface:

package main

import (
    "fmt"
)

type Comparer interface {
    // Less reports whether the element  is less than b
    Less(b interface{}) bool
}

func main() {
    a, b := Int(1), Int(2)
    fmt.Println(a.Less(b)) // true

    c, d := St("A"), St("B")
    fmt.Println(c.Less(d)) // true
}

type Int int

func (t Int) Less(b interface{}) bool {
    if v, ok := b.(Int); ok {
        return int(t) < int(v)
    }
    return false
}

type St string

func (t St) Less(b interface{}) bool {
    if v, ok := b.(St); ok {
        return string(t) < string(v)
    }
    return false
}

3- 使用reflect

【讨论】:

  • 你能给我一个简单的例子,说明你将如何在这种情况下使用 Less 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-29
  • 1970-01-01
相关资源
最近更新 更多