go语言实现虚函数功能

go没有虚函数,因此需要用这个来间接实现对派生对象函数的引用。

package main

import "fmt"

type dosomething interface {
	printhello()
	printworld()
	printgood()
}


type innerStruct struct {
	num int
	//functions dosomething
}

func (i *innerStruct) printhello() {
	fmt.Println("hello")
}


type outerStruct1 struct {
	*innerStruct
}

func (o *outerStruct1) printworld() {
	fmt.Println("world1")
}


type outerStruct2 struct {
	*innerStruct
}

func (o *outerStruct2) printworld() {
	fmt.Println("world2")
}


func main() {
	outer1 := outerStruct1{&innerStruct{num:123}}
	outer1.printhello()
	outer1.printworld()
	//outer1.functions = &outer1

	outer2 := outerStruct2{&innerStruct{num:123}}
	outer2.printhello()
	outer2.printworld()
	//outer2.functions = &outer2
}


/*
go没有虚函数,因此需要用这个来间接实现对派生对象函数的引用
不把interface放入结构体也是可以的
放入只是为了确保最终实现了所有函数
类似于虚函数,全部实现了那个类才能用
把它放进去,一层一层套用,最后实现了接口中所有函数,就可以用了


如果去掉上述代码中的注释,需要添加下列函数才行。

func (i *innerStruct) printgood() {
	fmt.Println("good")
}
*/

输出:

hello
world1
hello
world2

 

其他参考:

结构体中嵌入接口的作用

golang的struct里面嵌入interface

来自 <https://www.jianshu.com/p/a5bc8add7c6e>

嵌入interface可以使得一个struct具有interface的接口,而不需要实现interface中的有声明的函数。

Go编程之接口作结构体属性

来自 <https://blog.csdn.net/star199207/article/details/79054583>

目的是当前结构体实例可以用所有实现了该接口的其他结构体来初始化(即使他们的属性不完全一致)

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的Go语言实现文件上传和下载的示例代码: 上传文件: ``` func handleUpload(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } file, _, err := r.FormFile("file") if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } defer file.Close() // 将文件保存到本地 f, err := os.OpenFile("uploaded_file", os.O_WRONLY|os.O_CREATE, 0666) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer f.Close() io.Copy(f, file) w.WriteHeader(http.StatusOK) } ``` 下载文件: ``` func handleDownload(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } f, err := os.Open("uploaded_file") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer f.Close() // 设置响应头,告诉浏览器文件类型和文件名 w.Header().Set("Content-Type", "application/octet-stream") w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", "uploaded_file")) io.Copy(w, f) } ``` 在main函数中,可以将这两个函数绑定到HTTP路由上: ``` func main() { http.HandleFunc("/upload", handleUpload) http.HandleFunc("/download", handleDownload) http.ListenAndServe(":8080", nil) } ``` 现在,访问http://localhost:8080/upload可以上传文件,访问http://localhost:8080/download可以下载刚刚上传的文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值