運行以下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