英文:
Golang interface on type
问题
我是你的中文翻译助手,以下是你提供的代码的翻译:
package main
import "fmt"
type Sequence []float64
type Stats interface {
greaterThan(x float64) Sequence
}
func (s Sequence) greaterThan(x float64) Sequence {
var v Sequence
for _, num := range s {
if num > x {
v = append(v, num)
}
}
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)
}
这是修复后的代码,它定义了一个名为Sequence
的类型和一个名为Stats
的接口。greaterThan
方法接收一个float64
参数,并返回一个新的Sequence
,其中移除了所有小于等于该参数的数字。在修复后的代码中,我们使用了一个循环来遍历原始的Sequence
,并将大于给定参数的数字添加到新的Sequence
中。最后,我们在main
函数中创建了一个Sequence
对象并调用display
函数来展示结果。
关于你的问题,你不需要使用map
来删除结构类型中的元素。你可以使用切片来存储和操作Sequence
类型的数据。在修复后的代码中,我们使用了切片来存储新的Sequence
,并使用append
函数将符合条件的数字添加到切片中。
希望这可以帮助到你!如果你有任何其他问题,请随时问我。
英文:
I am new to GO and I am using golang to write a simple type interface.
The type is defined as:
type Sequence []float64
and the interface is:
type Stats interface {
greaterThan(x float64) Sequence
}
The function greaterThan(x float64)
should return a new Sequence that is the same as the numbers in the object
// except all numbers less than, or equal to, x have been removed.
Here is my try, but it will not compile. I don't know how to fix it.
My question is : how can I delete an item from structure type? Should I use a map? (as my try)
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)
}
答案1
得分: 4
我会这样做:
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
最可能的情况是,你不应该从切片中删除项目,而是构建一个只包含所需项目的新切片。
只是出于好奇:你想用接口Stats
做什么?
英文:
I'd do it like this:
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))
}
See http://play.golang.org/p/qXi5uE-25v
Most probably you should not delete items from the slice but construct a new one containing only the wanted ones.
Just out of curiosity: What do you want to do with the interface Stat?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论