zoukankan      html  css  js  c++  java
  • 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)
    }
    
    必须函数签名相同(函数名,参数和返回值(类型,个数,顺序)都相同),否则会转换失败,无法实现该接口。
  • 相关阅读:
    hadoop与spark的处理技巧(六)聚类算法(3)LDA
    hadoop与spark的处理技巧(一)Top N处理技巧
    从零开始学Python 三(网络爬虫)
    Could not get JDBC Connection--java
    idea函数被调用
    人工智能-我们应该了解什么(一)
    从零开始学Python 二
    从零开始学Python 一
    java8 简便的map和list操作
    Could not autowire. No beans of 'xxxx' type found的错误
  • 原文地址:https://www.cnblogs.com/l1ng14/p/14164419.html
Copyright © 2011-2022 走看看