老师:百忙之中,跪请解惑啊
//===============定义接口=======================
package interfaces
type TCPGet interface {
Get(url string) string
}
type TCPPost interface {
Post(url string) string
}
type TCP interface {
TCPGet
TCPPost
}
//=======定义实现===============================
package interfaces
type Http struct {
Content string
}
func (http Http) Get(url string) string {
return http.Content+"->this is get request"
}
func (http Http) Post(url string) string {
return http.Content+"->this is post request"
}
//=================主程序========================
const url ="http://www.baidu.com"
func main() {
var myhttpStruct = interfaces.Http{Content: "接口测试"}
//接口可以指向实现了该接口的结构体的指针,
//这个指针通过解地址就可以拿到这个结构体,
//问题1:老师,go语言中是不是实现了某个接口的结构体的指针都可以使用该接口去接收?
var http interfaces.TCP = &myhttpStruct
fmt.Printf("%T , %T ,%T\n",myhttpStruct,http,&http)
Myrequest(&http) //获取到这个接口的指针,也就是 这个结构体的指针的指针
var httpx * interfaces.TCP = &(&interfaces.Http{Content: "接口测试"})
//问题2,老师,为什么这种语法就不行呢?
fmt.Printf("%T\n",httpx)
}
func Myrequest(http * interfaces.TCP) {//这个
//http 是接口的指针,通过解一次地址获取到的是结构体的指针,通过结构体的指针调用该结构体下的方法
fmt.Printf("%T , %T\n",http,*http)
fmt.Println((*http).Get(url))
fmt.Println((*http).Post(url))
}
展开
作者回复: 第一个问题答案是“是”
第二个问题是因为
接口对应的是结构体的指针,我们不使用接口的指针(因为他指向的并不是实现接口的具体类型)
所以你的方法应该定义为
func Myrequest(http interfaces.TCP)