0Pricing
Go Academy · 강의

표준 라이브러리의 핵심 인터페이스

fmt.Stringer, io.Reader, io.Writer

표준 라이브러리의 핵심 인터페이스은(는) CoddyKit의 무료 Go Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Go Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Go Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

fmt.Stringer

fmt.Stringer에는 메서드가 하나 있습니다: String() string. 이를 구현하면 fmt.Println과 %v에서 타입이 표시되는 방식을 제어할 수 있습니다:

package main
import "fmt"

type Color int
const (Red Color = iota; Green; Blue)
func (c Color) String() string {
    return []string{"Red","Green","Blue"}[c]
}

func main() {
    fmt.Println(Red, Green, Blue) // Red Green Blue
}

error 인터페이스

내장 error 인터페이스에는 메서드가 하나 있습니다: Error() string. 이를 구현하는 모든 타입을 오류로 사용할 수 있습니다:

package main
import "fmt"

type ValidationError struct{ Field, Msg string }
func (e *ValidationError) Error() string {
    return e.Field + ": " + e.Msg
}

func validate(age int) error {
    if age < 0 { return &ValidationError{"age", "must be non-negative"} }
    return nil
}

func main() {
    fmt.Println(validate(-1))
}

io.Reader

io.Reader에는 메서드가 하나 있습니다: Read(p []byte) (n int, err error). 파일, HTTP 본문, 문자열, 버퍼가 모두 이를 구현합니다:

package main
import ("fmt"; "strings")

func countBytes(r interface{ Read([]byte)(int,error) }) int {
    buf := make([]byte, 512)
    total := 0
    for {
        n, err := r.Read(buf)
        total += n
        if err != nil { break }
    }
    return total
}

func main() {
    r := strings.NewReader("hello world")
    fmt.Println(countBytes(r)) // 11
}

io.Writer

io.Writer에는 메서드가 하나 있습니다: Write(p []byte) (n int, err error). fmt.Fprintf, 로깅, HTTP 응답 작성기 등에서 사용됩니다:

package main
import ("bytes"; "fmt")

func main() {
    var buf bytes.Buffer
    fmt.Fprintf(&buf, "Hello, %s!", "Go")
    fmt.Println(buf.String()) // Hello, Go!
}

io.ReadWriter와 io.Closer

표준 라이브러리는 작은 인터페이스를 더 큰 인터페이스로 조합합니다:

package main
import "io"

// io.ReadWriter = io.Reader + io.Writer
// io.ReadCloser = io.Reader + io.Closer
// io.ReadWriteCloser = all three

func process(rw io.ReadWriter) {
    buf := make([]byte, 8)
    rw.Read(buf)
    rw.Write(buf)
}

func main() { _ = process }

sort.Interface

sort.Interface에는 Len() int, Less(i, j int) bool, Swap(i, j int)이 필요합니다:

package main
import ("fmt"; "sort")

type ByLength []string
func (b ByLength) Len() int           { return len(b) }
func (b ByLength) Less(i, j int) bool { return len(b[i]) < len(b[j]) }
func (b ByLength) Swap(i, j int)      { b[i], b[j] = b[j], b[i] }

func main() {
    fruits := ByLength{"banana","apple","kiwi"}
    sort.Sort(fruits)
    fmt.Println([]string(fruits)) // [kiwi apple banana]
}

http.Handler

http.Handler에는 메서드가 하나 있습니다: ServeHTTP(ResponseWriter, *Request). Go의 HTTP 스택에 있는 모든 요소는 이 단일 인터페이스를 기반으로 만들어집니다:

package main
import ("fmt"; "net/http")

type Hello struct{}
func (h Hello) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello, World!")
}

func main() {
    http.ListenAndServe(":8080", Hello{})
}

fmt.GoStringer

GoString() string을 구현하면 타입의 %#v(Go 문법) 표현을 제어할 수 있습니다:

package main
import "fmt"

type Version struct{ Major, Minor int }
func (v Version) GoString() string {
    return fmt.Sprintf("Version{%d, %d}", v.Major, v.Minor)
}

func main() {
    fmt.Printf("%#v\n", Version{1, 18}) // Version{1, 18}
}

encoding.TextMarshaler

사용자 정의 텍스트 인코딩(JSON 문자열, YAML 등)을 위해 MarshalText() ([]byte, error)와 UnmarshalText([]byte) error를 구현합니다:

package main
import "fmt"

type Status int
const (Active Status = iota; Inactive)
func (s Status) MarshalText() ([]byte, error) {
    if s == Active { return []byte("active"), nil }
    return []byte("inactive"), nil
}

func main() {
    s := Active
    b, _ := s.MarshalText()
    fmt.Println(string(b)) // active
}

표준 인터페이스 조합하기

io.TeeReader, io.MultiWriter 등을 사용해 표준 인터페이스를 조합하면 새로운 타입을 작성하지 않고도 강력한 파이프라인을 만들 수 있습니다:

package main
import ("bytes"; "fmt"; "io"; "strings")

func main() {
    r := strings.NewReader("hello")
    var buf bytes.Buffer
    tee := io.TeeReader(r, &buf)
    io.ReadAll(tee)
    fmt.Println(buf.String()) // hello
}

빠른 확인

Go에서 타입을 오류로 사용하려면 어떤 인터페이스를 구현해야 합니까?

요약

주요 표준 라이브러리 인터페이스:

  • fmt.Stringer — 사용자 정의 출력 표현
  • error — 오류 값
  • io.Reader / io.Writer — 스트리밍 입출력
  • sort.Interface — 사용자 정의 정렬
  • http.Handler — HTTP 요청 처리

연습 과제

Person이 Name 및 Age 필드를 가진 []Person에 sort.Interface를 구현하여 나이를 기준으로 내림차순 정렬하십시오. 정렬된 목록을 출력하십시오.

자주 묻는 질문

“표준 라이브러리의 핵심 인터페이스” 강의는 무료인가요?

네 — “표준 라이브러리의 핵심 인터페이스” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Go Academy 강의 전체를 잠금 해제할 수 있습니다. Go Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“표준 라이브러리의 핵심 인터페이스”에서 뭘 배우나요?

fmt.Stringer, io.Reader, io.Writer 브라우저에서 직접 실행하는 실습 코드로 Go Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Go Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Go Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“표준 라이브러리의 핵심 인터페이스” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Go Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Go Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 인터페이스 정의와 구현
  2. 표준 라이브러리의 핵심 인터페이스
  3. 타입 단언과 타입 스위치
  4. 인터페이스 조합과 모범 사례
← Go Academy(으)로 돌아가기