Menu
CoddyTech

생성자 관례

Coddy의 C 개발자를 위한 Go 코스 레슨. 48개 중 28번째.

C 초기화는 API가 의존하는 모든 상태 필드를 설정해야 합니다. Go는 제로값을 제공하지만, 할당된 제로값 구조체가 도메인 불변 조건을 위반할 수도 있습니다. 팩터리 함수는 입력값을 검증할 수 있습니다. 한 객체가 다른 객체에 영향을 주지 않아야 한다면 변경 가능한 컬렉션은 인스턴스마다 할당하세요.

Go에는 특별한 생성자 구문이 없습니다. NewType 함수는 관례이며 오류를 반환할 수도 있습니다. 잘못된 상태가 반환값에 들어가지 않도록 하세요. 포인터 반환은 공유된 동일성을 제공할 수 있고, 작은 불변 레코드라면 값 반환이 적절할 수 있습니다.

C 예제

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
struct Score { int points; };
struct Score make_score(int points) { struct Score s = {points}; return s; }
int main(void) {
    struct Score a = make_score(4); struct Score b = make_score(0);
    a.points += 3;
    printf("%d %d\n", a.points, b.points);
    return 0;
}

소스 출력:

7 0

Go 예제

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
challenge icon

챌린지

쉬움

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)
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C 개발자를 위한 Go의 모든 레슨

직접 연습해 보세요: 온라인 Go 컴파일러