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 }
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
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 |
위 내용은 GoLang 구조체의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!