运行以下Go代码时出现以下编译器错误。Go的struct方法在调用中抛出太多参数
package sort
type InsertionSort struct {
Unsorted []int;
}
func (is InsertionSort) Sort(mode string) []int {
length := len(is.Unsorted);
funcs := map[string] func(int, int) bool {"method":is.greaterThan};
if mode == "desc" {
funcs = map[string] func(int, int) bool {"method":is.lesserThan};
}
for i := 0; i < length; i++ {
temp := is.Unsorted[i];
j := i - 1;
for ; j >=0 && funcs["method"](is.Unsorted[j], temp); j-- {
is.Unsorted[j + 1] = is.Unsorted[j];
}
is.Unsorted[j + 1] = temp;
}
return is.Unsorted;
}
func (is InsertionSort) greaterThan (a int, b int) bool {
return a > b;
}
func (is InsertionSort) lesserThan (a int, b int) bool {
return a < b;
}
,并具有调用函数由编译器返回
package main
import (
"learning/Go/testgo/sort"
"fmt"
)
func main() {
unsort := []int {5, 7, 3, 2 ,4 ,8, 9, 12, 1};
i := sort.InsertionSort {unsort};
mode := "asc";
sorted := i.Sort(mode);
fmt.Println(sorted);
}
错误消息的主包是
\ sort.go:16:调用的参数太多i.Sort
注: - 包sort已经有另一个名为BubbleSort的结构,它具有相同的没有参数的Sort方法。我不知道它是否与当前结构相冲突。
请帮我解决这个问题。
您是否尝试过重命名的方法来解决冲突? – fafl
@fafl,是的,我试过了。我在这两个软件包(sort&main)中替换了函数Sort和InSort。它返回以下错误。 ** i.InSort未定义(类型sort.InsertionSort没有字段或方法InSort)** –
您发布的代码的作品。请张贴您的完整代码或这个问题,因为它是无关紧要的。 – icza