Reputation: 123
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)
}
Upvotes: 0
Views: 1831
Reputation: 42458
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?
Upvotes: 4