Golang中私有变量的使用

在Go语言中,如果结构体中的变量是私有的(即小写字母开头),那么它们只能通过结构体的实例进行访问和修改。如果你想给结构体赋值,你需要先创建一个结构体的实例,然后通过该实例来访问和修改结构体的私有变量

示例代码:

复制代码
package main

import (
	"fmt"
)

// BaseFilter结构体定义了3个私有变量
type BaseFilter struct {
	bodyRaw interface{}
	query   string
	logID   string
}

// ANNFilter结构体定义了1个公有变量
type ANNFilter struct {
	BaseFilter
}

// 创建实例
func NewANNFilter() *ANNFilter {
	return &ANNFilter{
		BaseFilter: BaseFilter{},
	}
}

func (bf *BaseFilter) ParseRequest(name string) error {
	// 通过实例方法设置私有变量的值
	bf.query = "hello world"
	fmt.Println(name)
	fmt.Println(bf.query)
	return nil
}

func (anf *ANNFilter) Process() error {
	// ANNFilter可以使用它公有变量的共有方法
	anf.ParseRequest("ANNFilter")
	return nil
}

func main() {
	anf := NewANNFilter()
	anf.Process()
	anf.ParseRequest("BaseFilter")
}

输出结果

复制代码
[work@aaa xxx]$ go run test.go
/home/work/.deck/1.0/go/1.21/bin/go run test.go
ANNFilter
hello world
BaseFilter
hello world
相关推荐
eggwyw8 分钟前
关于C++为什么不加入垃圾回收机制解析
开发语言·c++
jktantan9 分钟前
注解式脱敏:用 Jackson 的 ContextualSerializer 做字段级策略(一)
spring boot·后端·算法·spring cloud·系统架构
独泪了无痕9 小时前
探索Pinyin4j-Java中的拼音转换利器
java·后端
码事漫谈9 小时前
从 Coze 居然要下线了说起
后端
想不到一个好的ID10 小时前
智能体开发
后端
皮皮林55110 小时前
为什么数据库连接池不采用 IO 多路复用?
后端
来让爷抱一个11 小时前
Python 异步里混用同步库,事件循环被卡住的全过程
开发语言·python
IT_陈寒14 小时前
Redis雪崩把我坑惨了,这是5年经验的教训
前端·人工智能·后端
量化分析码农14 小时前
【Python量化多因子实战 06】从因子到持仓:多因子选股实盘工程化落地
后端
心祭丫丫14 小时前
【每天一个 Python 小案例17】Python 实现通讯录
开发语言·人工智能·笔记·python·学习