Go 中的指针解引用:发生了什么?
深入研究 Go 中的编程世界时,您可能会遇到与指针解引用相关的有趣行为,特别是当使用结构。考虑以下示例:
package main import "fmt" type Vertex struct { X, Y int } var ( p = Vertex{1, 2} // has type Vertex q = &Vertex{1, 2} // has type *Vertex r = Vertex{X: 1} // Y:0 is implicit s = Vertex{} // X:0 and Y:0 ) func main() { t := *q q.X = 4 u := *q fmt.Println(p, q, r, s, t, u, t == u) }
运行此代码会产生令人惊讶的结果:
{1 2} &{4 2} {1 0} {0 0} {1 2} {4 2} false
您可能期望 t 在更改 q.X 后更改为 {4, 2},但这并不发生。这种行为的原因是什么?
指针解引用解释
理解这一点的关键是指针解引用。在 Go 中,当您取消引用指针(例如 *q)时,您会创建它指向的值的副本。因此, t := *q 制作 q 引用的 Vertex 结构的单独副本。
示例 28 的修改说明:
在修改后的示例中,当您设置q.X = 4,您仅修改 q 指向的结构。由于 t 是一个副本,因此它保留了其原始值。
比较 Go 和 C/C
您提到了从 C/C 角度来看似乎很奇怪的行为。然而,C/C 的行为类似。考虑这个例子:
#include <iostream> struct Vertex { int x; int y; }; int main() { Vertex v = Vertex{1, 2}; Vertex* q = &v; Vertex t = *q; q->x = 4; std::cout <p>这个 C 代码产生相同的行为:</p> <pre class="brush:php;toolbar:false">*q: { 4, 2 } t: { 1, 2 }
结论
总之,当你在 Go 中取消引用指针时,你'重新创建基础价值的副本。要观察通过指针所做的更改,您必须使用指针本身,如修改后的示例所示:
func main() { t := q q.X = 4 u := *q fmt.Println(p, q, r, s, t, u, *t == u) }
这将产生 {1 2} &{4 2} {1 0} 的预期输出{0 0} {4 2} {4 2} 正确。
以上是为什么在 Go 中取消引用指针不会修改原始值?的详细内容。更多信息请关注PHP中文网其他相关文章!

有效的Go应用错误日志记录需要平衡细节和性能。1)使用标准log包简单但缺乏上下文。2)logrus提供结构化日志和自定义字段。3)zap结合性能和结构化日志,但需要更多设置。完整的错误日志系统应包括错误enrichment、日志级别、集中式日志、性能考虑和错误处理模式。

EmptyinterfacesinGoareinterfaceswithnomethods,representinganyvalue,andshouldbeusedwhenhandlingunknowndatatypes.1)Theyofferflexibilityforgenericdataprocessing,asseeninthefmtpackage.2)Usethemcautiouslyduetopotentiallossoftypesafetyandperformanceissues,

go'sconcurrencyModelisuniqueduetoItsuseofGoroutinesandChannels,offeringaleightweightandefficePparreactComparredTothread-likeModelsInlanguagesLikeLikejava,python,andrust.1)

go'sconcurrencyModeluessgoroutinesandChannelStomanageConconCurrentPrommmengement.1)GoroutinesArightweightThreadThreadSthAtalLeadSthAtalAlaLeasyParalleAftasks,增强Performance.2)ChannelsfacilitatesfacilitatesafeDataTaAexafeDataTaAexchangeBetnegnegoroutinesGoroutinesGoroutinesGoroutinesGoroutines,crucialforsforsynchrroniz

Interfaceand -polymormormormormormingingoenhancecodereusability and Maintainability.1)DewineInterfaceSattherightabStractractionLevel.2)useInterInterFacesForceFordEffeldIndentientIndoction.3)ProfileCodeTomanagePerformanceImpacts。

TheinitfunctioninGorunsautomaticallybeforethemainfunctiontoinitializepackagesandsetuptheenvironment.It'susefulforsettingupglobalvariables,resources,andperformingone-timesetuptasksacrossanypackage.Here'showitworks:1)Itcanbeusedinanypackage,notjusttheo

接口组合在Go编程中通过将功能分解为小型、专注的接口来构建复杂抽象。1)定义Reader、Writer和Closer接口。2)通过组合这些接口创建如File和NetworkStream的复杂类型。3)使用ProcessData函数展示如何处理这些组合接口。这种方法增强了代码的灵活性、可测试性和可重用性,但需注意避免过度碎片化和组合复杂性。

initfunctionsingoareAutomationalCalledBeLedBeForeTheMainFunctionandAreuseFulforSetupButcomeWithChallenges.1)executiondorder:totiernitFunctionSrunIndIndefinitionorder,cancancapationSifsUsiseSiftheyDepplothother.2)测试:sterfunctionsmunctionsmunctionsMayInterfionsMayInterferfereWithTests,b


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Dreamweaver Mac版
视觉化网页开发工具

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

禅工作室 13.0.1
功能强大的PHP集成开发环境