Maison > développement back-end > Golang > le corps du texte

Portées de champ Golang Struct

王林
Libérer: 2024-08-31 20:30:41
original
1102 Les gens l'ont consulté

Portées des champs de structure

Champs exportés

Dans d'autres langues, cela serait similaire au qualificatif d'accès public.

  • Si vous venez de Ruby comme moi, cela définirait des attributs avec attr_accessor

Si le champ (c'est-à-dire l'attribut) de la structure commence par une majuscule, cela signifierait que ce champ est exporté, donc accessible en dehors du package.

Supposons que nous ayons les fichiers suivants dans le projet Go :

main.go
/library
  /book.go
Copier après la connexion

Nous définirions book.go dans son propre package.

// 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
}
Copier après la connexion

Lors de son utilisation dans 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)
}
Copier après la connexion

En Ruby, cela serait synonyme d'utiliser attr_accessor puisqu'on peut :

  • lire et écrire les valeurs d'attribut en dehors de la classe
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
Copier après la connexion

Champs privés

Ceci est similaire aux qualificatifs d'accès privé dans d'autres langues

S'il commence par une minuscule, les champs ne seront pas accessibles.

Essayez-le par vous-même !

En supposant que le nom de votre module est myapp dans go.mod

// go.mod
module myapp

go 1.22.5
Copier après la connexion

Nous créons un nouveau fichier dans library/book.go sous le package library

// 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
}
Copier après la connexion

Importez le package dans 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)
}
Copier après la connexion

Si vous avez configuré Go dans VSCode, vous obtiendrez l'erreur de charpie suivante sur la ligne :

  • titre : "Titre du livre

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
Copier après la connexion

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:dev.to
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!