gpt4 book ai didi

pointers - 将局部变量的指针传递给 Golang 中的 channel 是否安全?

转载 作者:IT王子 更新时间:2023-10-29 01:02:16 26 4
gpt4 key购买 nike

我有一个查询 AD 并检索结果并写入 channel 的代码块。

func GetFromAD(connect *ldap.Conn, ADBaseDN, ADFilter string, ADAttribute []string, ADPage uint32) *[]ADElement {

searchRequest := ldap.NewSearchRequest(ADBaseDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, ADFilter, ADAttribute, nil)
sr, err := connect.SearchWithPaging(searchRequest, ADPage)
CheckForError(err)
fmt.Println(len(sr.Entries))
ADElements := []ADElement{}
for _, entry := range sr.Entries{
NewADEntity := new(ADElement) //struct
NewADEntity.DN = entry.DN
for _, attrib := range entry.Attributes {
NewADEntity.attributes = append(NewADEntity.attributes, keyvalue{attrib.Name: attrib.Values})
}
ADElements = append(ADElements, *NewADEntity)
}
return &ADElements
}

上述函数返回一个指向[]ADElements的指针。

在我的 initialrun 函数中,我这样调用这个函数

ADElements := GetFromAD(connectAD, ADBaseDN, ADFilter, ADAttribute, uint32(ADPage))
fmt.Println(reflect.TypeOf(ADElements))
ADElementsChan <- ADElements

输出是

*[]somemodules.ADElement

作为 reflect.TypeOf 的输出。

我的疑问是,由于 GetFromAD() 中定义的 ADElements := []ADElement{} 是局部变量,因此必须在堆栈中分配它,并且当 GetFromAD() 退出,堆栈的内容必须被销毁,并且对 GetFromAD() 的进一步引用必须指向无效的内存引用,而我仍然得到 返回的元素的确切数量GetFromAD() 没有任何段错误。这是如何工作的?这样做安全吗?

最佳答案

是的,它是安全的,因为 Go 编译器执行逃逸分析并在堆上分配此类变量。

查看 FAQ - How do I know whether a variable is allocated on the heap or the stack?

The storage location does have an effect on writing efficient programs. When possible, the Go compilers will allocate variables that are local to a function in that function's stack frame. However, if the compiler cannot prove that the variable is not referenced after the function returns, then the compiler must allocate the variable on the garbage-collected heap to avoid dangling pointer errors. Also, if a local variable is very large, it might make more sense to store it on the heap rather than the stack.

关于pointers - 将局部变量的指针传递给 Golang 中的 channel 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35649171/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com