Menu
CoddyTech

값 리시버 메서드

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

C# 인스턴스 메서드는 선언된 클래스 또는 구조체의 멤버입니다. Go 메서드는 타입 정의 바깥에 리시버를 지정합니다. T와 *T 중 무엇을 선택하느냐에 따라 복사 및 변경 동작이 결정되며, 이는 접근 제한자가 아닙니다.

메서드는 이름 앞에 리시버가 오는 함수입니다. 값 리시버는 리시버의 복사본을 받습니다. 메서드는 같은 패키지에 정의된 비인터페이스 타입에 연결할 수 있습니다. Go에서는 메서드를 둘러싼 클래스 본문이 필요하지 않습니다.

C# 예제

using System;
using System.Collections.Generic;
using System.Linq;
struct Word{string text;public Word(string s){text=s;}public string Loud(){return text.ToUpperInvariant();}}
class Program { static void Main() {
Console.WriteLine(new Word("go").Loud());
} }

소스 출력:

GO

Go 예제

package main
import ("fmt";"strings")
type Word string
func(w Word) Loud() string { return strings.ToUpper(string(w)) }
func main(){fmt.Println(Word("go").Loud())}

Go 출력:

GO
challenge icon

챌린지

쉬움

Width와 Height int 필드가 있고, 너비와 높이를 곱한 값을 반환하는 Area() int 메서드가 있는 Rectangle을 정의하세요. 입력값은 0 이상 100 이하의 치수입니다.

선언된 API를 구현하고, 출력하지 말고 결과를 반환하세요. 드라이버는 필수 API를 확인하고 호출자의 입력을 보존합니다. 컬렉션의 표준 출력에는 JSON이 아닌 Go의 대괄호 형식이 사용됩니다.

코드는 rectangle.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)
a1:=I(1); before1:=fmt.Sprint(a1)
must((Rectangle{3,5}).Area()==15 && (Rectangle{0,4}).Area()==0,"Area API");
result:=Solve(a0,a1)
must(fmt.Sprint(a0)==before0,"input mutation")
must(fmt.Sprint(a1)==before1,"input mutation")
fmt.Println(result)
}
quiz icon실력 점검

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

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

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