>  기사  >  백엔드 개발  >  인터페이스를 사용하여 Go 함수를 일반화하는 방법: 유형 제약 솔루션

인터페이스를 사용하여 Go 함수를 일반화하는 방법: 유형 제약 솔루션

DDD
DDD원래의
2024-10-27 02:28:30342검색

 How to Make Go Functions Generic Using Interfaces: A  Type Constraint Solution

Go의 일반 메소드 매개변수: 유형 제약 문제 해결

문제:

다음 Go 코드를 고려해 보세요.

<code class="go">package main

import (
    "fmt"
    "strconv"
)

type Mammal struct {
    ID int
    Name string
}

type Human struct {
    ID int
    Name string
    HairColor string
}

func Count(ms []Mammal) *[]string {
    IDs := make([]string, len(ms))
    for i, m := range ms {
        IDs[i] = strconv.Itoa(int(m.ID))
    }
    return &IDs
}

func main() {
    ... // Code to create Mammal and Human slices
    numberOfMammalIDs := Count(mammals)
    numberOfHumanIDs := Count(humans)
    fmt.Println(numberOfMammalIDs)
    fmt.Println(numberOfHumanIDs)
}</code>

이 코드는 오류 오류 prog.go:39와 함께 컴파일되지 않습니다. Count에 대한 인수에서 인간([]Human 유형)을 []Mammal 유형으로 사용할 수 없습니다. 문제는 Count 함수가 Mammal 구조체 배열을 기대하지만 Human 구조체 배열을 전달하기 때문에 발생합니다. 이 유형 제약 조건을 어떻게 해결하고 ID 속성이 있는 모든 유형을 허용할 만큼 충분히 일반적인 Count 함수를 만들 수 있습니까?

해결책:

1. 인터페이스 사용:

구체적인 유형을 ID 속성을 정의하는 인터페이스로 바꾸세요. 예:

<code class="go">type Mammal interface {
    GetID() int
}

type Human interface {
    Mammal
    GetHairColor() string
}</code>

2. 내장 인터페이스:

Mammal 및 Human 인터페이스 모두에서 ID 방법이 중복되지 않도록 하려면 내장 인터페이스를 사용하십시오:

<code class="go">type MammalImpl struct {
    ID int
    Name string
}

func (m MammalImpl) GetID() int {
    return m.ID
}

type HumanImpl struct {
    MammalImpl
    HairColor string
}</code>

3. 카운트 함수 업데이트:

구체적인 Mammal 유형 대신 Mammal 인터페이스를 사용하도록 Count 함수 수정:

<code class="go">func Count(ms []Mammal) *[]string {
    IDs := make([]string, len(ms))
    for i, m := range ms {
        IDs[i] = strconv.Itoa(m.GetID())
    }
    return &IDs
}</code>

4. 인터페이스 호환 슬라이스 생성:

포유류 인터페이스를 구현하는 슬라이스 생성:

<code class="go">mammals := []Mammal{
    MammalImpl{1, "Carnivorious"},
    MammalImpl{2, "Ominivorious"},
}

humans := []Mammal{
    HumanImpl{MammalImpl: MammalImpl{ID: 1, Name: "Peter"}, HairColor: "Black"},
    HumanImpl{MammalImpl: MammalImpl{ID: 2, Name: "Paul"}, HairColor: "Red"},
}</code>

5. 사용 예:

이제 성공적으로 컴파일되는 사용 예:

<code class="go">package main

import (
    "fmt"
    "strconv"
)

type Mammal interface {
    GetID() int
}

type Human interface {
    Mammal
    GetHairColor() string
}

type MammalImpl struct {
    ID   int
    Name string
}

func (m MammalImpl) GetID() int {
    return m.ID
}

type HumanImpl struct {
    MammalImpl
    HairColor string
}

func (h HumanImpl) GetHairColor() string {
    return h.HairColor
}

func Count(ms []Mammal) *[]string {
    IDs := make([]string, len(ms))
    for i, m := range ms {
        IDs[i] = strconv.Itoa(m.GetID())
    }
    return &IDs
}

func main() {
    mammals := []Mammal{
        MammalImpl{1, "Carnivorious"},
        MammalImpl{2, "Ominivorous"},
    }

    humans := []Mammal{
        HumanImpl{MammalImpl: MammalImpl{ID: 1, Name: "Peter"}, HairColor: "Black"},
        HumanImpl{MammalImpl: MammalImpl{ID: 2, Name: "Paul"}, HairColor: "Red"},
    }

    numberOfMammalIDs := Count(mammals)
    numberOfHumanIDs := Count(humans)
    fmt.Println(numberOfMammalIDs) // [1 2]
    fmt.Println(numberOfHumanIDs) // [1 2]
}</code>

인터페이스와 임베디드 인터페이스를 사용하여 다음을 구현하는 모든 유형을 처리할 수 있을 만큼 충분히 일반적인 Count 함수를 만들었습니다. 포유동물 인터페이스로 유형 제약 문제를 효과적으로 해결합니다.

위 내용은 인터페이스를 사용하여 Go 함수를 일반화하는 방법: 유형 제약 솔루션의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.