Menu
CoddyTech

생성자 관례

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

C# 생성자는 새 클래스나 구조체를 초기화하며 예외를 발생시킬 수 있습니다. Go에서 생성자와 유사한 함수는 일반 함수이며, 흔히 (*T,error)를 반환합니다. Go에는 생성자 오버로딩이 없고, 외부에서 볼 수 있는 구조체의 제로 값을 사용하기 위해 생성자를 반드시 호출해야 하는 것도 아닙니다.

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

C# 예제

using System;
using System.Collections.Generic;
using System.Linq;
class Greeting{public string Text;public Greeting(string name){Text="Hello "+name;}}
class Program { static void Main() {
Console.WriteLine(new Greeting("Ada").Text);
} }

원본 출력:

Hello Ada

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를 확인하고 호출자의 입력을 보존합니다. 컬렉션의 stdout 출력은 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 컴파일러