【问题标题】:Golang interface on typeGolang 接口类型
【发布时间】:2014-02-04 12:12:28
【问题描述】:

我是 GO 新手,我正在使用 golang 编写一个简单的类型接口。 类型定义为:

type Sequence []float64

and the interface is:

type Stats interface {

        greaterThan(x float64) Sequence
}

函数greaterThan(x float64) 应该返回一个与对象中的数字相同的新序列 // 除了所有小于或等于 x 的数字已被删除。

这是我的尝试,但它不会编译。我不知道如何解决它。 我的问题是:如何从结构类型中删除项目?我应该使用地图吗? (作为我的尝试)

package main

import "fmt"

type Sequence []float64

type Stats interface {

        greaterThan(x float64) Sequence
}

func (s Sequence) greaterThan(x float64) Sequence{

    var i int
    var f float64
    set := make(map[float64]int)
    var v = f[i] Sequence

    for i, f := range set{

    for j := 0; j <= len(s); j++ {
        if s[j] <= x {
        delete(set, s[j])
        }
    }
}

    return v
}

func display(s Sequence) {

        fmt.Println("s.greaterThan(2):", s.greaterThan(2))

}

func main() {

        s := Sequence([]float64{1, 2, 3, -1, 6, 3, 2, 1, 0})
        display(s)

}

【问题讨论】:

  • 编译尝试会显示哪些错误消息?
  • 顺便说一句。如所见heredelete 将地图(在您的情况下为set)和密钥(在您的情况下为j)作为参数。所以删除调用看起来像delete(set, i) 而不是delete(set, s[j])

标签: interface struct go


【解决方案1】:

我会这样做:

package main
import "fmt"
type Sequence []float64
type Stats interface {
    greaterThan(x float64) Sequence
}

func (s Sequence) greaterThan(x float64) (ans Sequence) {
    for _, v := range s {
        if v > x {
            ans = append(ans, v)
        }
    }
    return ans
}

func main() {
    s := Sequence{1, 2, 3, -1, 6, 3, 2, 1, 0}
    fmt.Printf("%v\n", s.greaterThan(2))
}

http://play.golang.org/p/qXi5uE-25v

您很可能不应该从切片中删除项,而是构建一个仅包含所需项的新项。

只是出于好奇:你想用接口 Stat 做什么?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-17
    • 2016-11-18
    • 2022-01-18
    • 1970-01-01
    • 2016-10-12
    • 2022-06-16
    • 2013-08-02
    • 1970-01-01
    相关资源
    最近更新 更多