GoLang 구조체

WBOY
풀어 주다: 2024-08-30 06:41:06
원래의
486명이 탐색했습니다.

GoLang Structs

Golang에서 구조체는 데이터를 담는 간단한 컨테이너입니다.

  • 필드를 가질 수 있음
  • 연결된 메서드가 없습니다.
    • 별도로 정의되고 구조체 유형과 연결된 메서드

다음은 Ruby 및 GoLang에서 이에 상응하는 간단한 Book 클래스를 보여줍니다.

class Book
  attr_reader(:title, :author)

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

# usage
book = Book.new('Title', 'Jon Snow')
로그인 후 복사
// Equivalent to `class Book` in ruby
type Book struct {
  Title string,
  Author string
}
로그인 후 복사

GoLang 유형 인스턴스화

복합 리터럴

Composite Literal은 한 단계로 초기화 복합 유형을 생성하는 구문입니다. 다음 유형을 인스턴스화할 수 있습니다.

  • 구조체
  • 배열
  • 슬라이스
  • 지도

여기서는 변수 book에 새로운 Book 인스턴스를 할당합니다

// Composite Literal
book := Book{
  Title: "Title",
  Author: "Author"
}
로그인 후 복사

새 키워드 사용

더 긴 형식은 new 키워드를 사용하는 것입니다. 이는 Ruby에서 book = Book.new(..)

를 사용하여 클래스를 인스턴스화하는 방식과 유사합니다.

= 기호를 사용하여 책의 속성(예: 제목 및 저자)을 할당합니다.

// Using the `new` keyword
book        := new(Book)
book.Title  = "Book Title"
book.Author = "John Snow"
로그인 후 복사

짧은 변수 선언 없이(:=)

첫 번째 예에서 := 기호를 사용했다는 점에 주목하세요.

변수를 선언하고 값을 할당하는 다음과 같은 장황한 방법에 대한 간단한 구문입니다.

// Without Short Virable Declaration

// Example 1
var book Book // Declare variable `book` of type `Book`
book.Title = "Book Title" // Assign the value to book variable
book.Author = "John Snow"

// Example 2
var count int
count = 20
로그인 후 복사

공장 기능

다음과 같은 경우에 구조체를 더 쉽게 초기화할 수 있도록 팩토리 패턴을 사용할 수도 있습니다.

  • 로직 추가
  • 기본값 추가

책 제목과 저자 토큰의 첫 글자를 모두 대문자로 만들고 싶다고 가정합니다.

// Factory Function
func NewBook(title string, author string) Book {
  return Book{
    Title: titlelise(title), // default logic to "titlelise" 
    Author: titlelist(author)
  }
}

func titlelise(str string) {
  caser := cases.Title(lanaguage.English)
  return caser.String(str)
}
로그인 후 복사

구조체에 함수 연결하기

Ruby에서는 클래스 내에 함수를 정의하기만 하면 됩니다. 여기서는 책 제목 이름 작성자를 인쇄하기 위해 to_string()이라는 함수를 정의하고 있습니다.

class Book
  attr_reader(:title, :author)

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

  # new function we added
  def to_string()
    put "#{title} by #{string}"
  end
end
로그인 후 복사

GoLang에서는 stuct를 함수에 전달하여 함수를 "연결"합니다.

// Equivalent to `class Book` in ruby
type Book struct {
  Title string,
  Author string
}

// Attaching the function to the `struct`
func (book Book) ToString() string {
  return fmt.Sprintf("%s by %s", book.Title, book.Author)
}

// Usage
book := Book{
  Title: "Title",
  Author: "Author"
}

book.ToString()
// => Title by Author
로그인 후 복사

설명:

func (book Book) ToString() string
로그인 후 복사
토큰 설명 기능 함수 키워드 (책 책) Book 구조체 유형에 함수 연결
Token Description
func function keyword
(book Book) Attaching the function to the type Book struct
- book: variable to access the struct within the function
- Book: type of the struct
ToString() name of the function
string return type of the function
- book: 함수 내의 구조체에 액세스하기 위한 변수- Book: 구조체 유형 ToString() 함수 이름 문자열 함수 반환 유형

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

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!