생성자 관례
Coddy의 C++ 개발자를 위한 Go 코스 레슨. 48개 중 28번째.
C++의 RAII는 리소스의 수명을 객체의 소멸 및 스코프와 연결합니다. Go의 가비지 컬렉션은 메모리를 관리하지만 외부 리소스를 적시에 해제하지는 않습니다. 명시적인 Close 스타일 메서드를 사용하고, 획득에 성공한 후 defer를 사용하세요. 독립적인 인스턴스 컬렉션은 의도적으로 할당하세요. 구조체를 복사해도 슬라이스나 맵은 여전히 공유될 수 있습니다.
Go에는 특별한 생성자 문법이 없습니다. NewType 함수는 관례일 뿐이며 오류를 반환할 수도 있습니다. 반환된 값에 유효하지 않은 상태가 포함되지 않도록 하세요. 포인터를 반환하면 공유된 정체성을 제공할 수 있으며, 작은 불변 레코드에는 값을 반환하는 것이 적절할 수 있습니다.
C++ 예제
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
int main() {
struct Score {
int points;
explicit Score(int initial = 0) : points(initial) {}
};
Score a(5), b;
std::cout << a.points << ' ' << b.points << '\n';
}소스 출력:
5 0Go 예제
package main
import ("fmt")
type Greeting struct { Text string }; func NewGreeting(name string) Greeting { return Greeting{Text:"Hello "+name} }
func main(){p:=NewGreeting("Ada")
fmt.Println(p.Text)}Go 출력:
Hello Ada챌린지
쉬움NewAccount(balance int) (*Account,error)를 구현하세요. 잔액이 음수이면 nil과 nil이 아닌 오류를 반환하고, 그 외의 잔액이면 Balance()가 해당 잔액과 일치하는 계정을 반환하세요. 잔액 하나를 입력합니다.
선언된 API를 구현하고, 출력하지 말고 결과를 반환하세요. 드라이버는 필요한 API를 확인하고 호출자의 입력을 보존합니다. 컬렉션의 표준 출력은 JSON이 아니라 Go의 대괄호 형식을 사용합니다.
코드는 account.go, exercise.go에 작성하세요. main.go에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다. 하나의 평면적인 package main을 유지하고 두 번째 main을 추가하지 마세요.
직접 해보기
package main
import ("fmt";"strings";"strconv";"bufio";"os")
var input []string
func L(i int)string{if i<len(input){return input[i]};return ""}
func I(i int)int{n,e:=strconv.Atoi(L(i));if e!=nil{panic(e)};return n}
func Ints(i int)[]int{out:=[]int{};if L(i)==""{return out};for _,s:=range strings.Split(L(i),","){n,e:=strconv.Atoi(s);if e!=nil{panic(e)};out=append(out,n)};return out}
func Words(i int)[]string{if L(i)==""{return []string{}};return strings.Split(L(i),",")}
func must(ok bool,message string){if !ok{panic("API: "+message)}}
func main(){
scanner:=bufio.NewScanner(os.Stdin);for scanner.Scan(){input=append(input,scanner.Text())};if scanner.Err()!=nil{panic(scanner.Err())}
a0:=I(0); before0:=fmt.Sprint(a0)
a,e:=NewAccount(7); must(e==nil && a!=nil && a.Balance()==7,"constructor API"); a,e=NewAccount(-1); must(a==nil && e!=nil,"constructor rejection");
result:=Solve(a0)
must(fmt.Sprint(a0)==before0,"input mutation")
fmt.Println(result)
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C++ 개발자를 위한 Go의 모든 레슨
직접 연습해 보세요: 온라인 Go 컴파일러