【发布时间】: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)
}
【问题讨论】:
-
编译尝试会显示哪些错误消息?
-
顺便说一句。如所见here
delete将地图(在您的情况下为set)和密钥(在您的情况下为j)作为参数。所以删除调用看起来像delete(set, i)而不是delete(set, s[j])