Golang–函數簽名相同
Golang–函數簽名相同
條件
必須函數的函數名,參數和返回值(類型,個數,順序)都相同。
驗證
例子:
定義函數類型,讓相同簽名的函數自動實現某個介面。
Negtive
:
package interfaceTest
import (
"fmt"
"testing"
)
type IntString interface {
test(a int ,s string) (int ,string)
}
type likeIntString func(s string ,i int) (int ,string)
func (i likeIntString) testaaa(ii int, s string) (int, string) {
return i(s, ii)
}
func TestInterface(t *testing.T){
var tt IntString = likeIntString(func(s string, i int) (int, string) {
return i,s
})
i, s := tt.testaaa(7, "dfdf")
fmt.Println(i,s)
}
# Go_test/src/interface/interfaceTest [Go_test/src/interface/interfaceTest.test]
.\interface_test.go:21:6: cannot use likeIntString(func literal) (type likeIntString) as type IntString in assignment:
likeIntString does not implement IntString (missing test method)
.\interface_test.go:25:12: tt.testaaa undefined (type IntString has no field or method testaaa)
Postive
package interfaceTest
import (
"fmt"
"testing"
)
type IntString interface {
test(a int ,s string) (int ,string)
}
type likeIntString func(s string ,i int) (int ,string)
func (i likeIntString) test(ii int, s string) (int, string) {
return i(s, ii)
}
func TestInterface(t *testing.T){
var tt IntString = likeIntString(func(s string, i int) (int, string) {
return i,s
})
i, s := tt.test(7, "dfdf")
fmt.Println(i,s)
}