>  기사  >  백엔드 개발  >  Golang 구조체 필드 범위

Golang 구조체 필드 범위

王林
王林원래의
2024-08-31 20:30:41945검색

구조체 필드 범위

내보낸 필드

다른 언어에서는 공개 액세스 한정자와 유사합니다.

  • 저처럼 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.mod에서 모듈 이름이 myapp이라고 가정

// go.mod
module myapp

go 1.22.5

패키지 라이브러리 아래 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 Struct Field Scopes

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

위 내용은 Golang 구조체 필드 범위의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.