总结
豆包 AI 助手文章总结
首页 > 后端开发 > Golang > 正文

Golang 结构字段范围

王林
发布: 2024-08-31 21:10:20
转载
443人浏览过

结构字段范围

导出字段

在其他语言中,这类似于公共访问限定符。

  • 如果你像我一样来自 ruby,这将使用 attr_accessor 定义属性

如果结构体的字段(即属性)以大写开头,则意味着该字段已导出,因此可以在包外部访问。

假设go项目中有以下文件:

main.go
/library
  /book.go
登录后复制

我们将在它自己的包中定义 book.go。

// library/book.go

// assume we have a package called "library" which contains a book.
package library

// struct that represents a physical book in a library with exported fields
type book struct {
  title string, 
  author string
}
登录后复制

在main.go中使用时:

package main

import (
  "fmt"
  "library" // importing the package that the struct book is in
)

func main() {
  book := library.book{
    title: "book title",
    author: "john snow"
  }
  // print the title and author to show that the struct book fields are accessible outisde it's package "library"
  fmt.println("title:", book.title)
  fmt.println("author:", book.author)
}
登录后复制

在 ruby 中,这与使用 attr_accessor 是同义的,因为我们可以:

  • 在类外读写属性值
class book
  # allow read and write on the attributes from outside the class
  attr_accessor(:title, :author)

  def initalize(title = nil, author = nil)
    @title  = title
    @author = authoer
  end
end

# usage outside of the class
book = book.new()

# assinging attributes outside of the class
book.title = "book title"
book.title = "jon snow"

# accessing attributes outside of the class
puts book.title, book.author
登录后复制

私人领域

这类似于其他语言中的私有访问限定符

如果以小写开头,则这些字段将不可访问。

立即学习go语言免费学习笔记(深入)”;

亲自尝试一下!

假设你的模块名称是 go.mod 中的 myapp

// go.mod
module myapp

go 1.22.5
登录后复制

我们在包library下的library/book.go中创建一个新文件

// library/book.go

// assume we have a package called "library" which contains a book.
package library

// fields start with lowercase, fields are not exported
type book struct {
  title string
  author string
}
登录后复制

将包导入main.go

// main.go
package main

import (
  "fmt"
  // import the library package
  "myapp/library"
)

func main() {
  book := library.book{
    title: "book title",
    author: "john snow"
  }
  // print the title and author to show that the struct book fields are accessible outisde it's package "library"
  fmt.println("title:", book.title)
  fmt.println("author:", book.author)
}
登录后复制

如果您在 vscode 中设置了 go,您会收到以下 lint 错误:

  • 标题:“书名

Golang 结构字段范围

unknown field author in struct literal of type library.Bookcompiler[MissingLitField](https://pkg.go.dev/golang.org/x/tools/internal/typesinternal#MissingLitField
登录后复制

以上就是Golang 结构字段范围的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
豆包 AI 助手文章总结
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号