"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > Embedding이 GO에서 복잡한 구조 계층 구현을 어떻게 개선 할 수 있습니까?

Embedding이 GO에서 복잡한 구조 계층 구현을 어떻게 개선 할 수 있습니까?

2025-03-24에 게시되었습니다
검색:719

How Can Embedding Improve Complex Structural Hierarchy Implementation in Go?

빈 메소드 이해

빈 메소드는 두 가지 주요 목적을 제공합니다. 인터페이스, 비 호환 유형을 서로 할당 할 수 없도록 보장합니다.

문서 :

그들은 유형별로 인터페이스의 구현을 명시 적으로 문서화하고 관계를 명확하게합니다.

분야와 방법, 상속의 형태를 만듭니다. 적절한 구조물을 계층 적 방식으로 내놓아 빈 방법의 필요성을 줄일 수 있습니다.

Object
--Immovable
----Building
----Mountain
--Movable
----Car
----Bike

type Object interface {
  object()
}

type ObjectImpl struct {}

func (o *ObjectImpl) object() {}

객체 구현 :

type Immovable interface {
  Object
  immovable()
}

type ImmovableImpl struct {
  ObjectImpl // Embedded Object implementation
}

func (i *ImmovableImpl) immovable() {}

부동 구현 :

type Building struct {
  ImmovableImpl // Embedded Immovable implementation
  // Additional Building-specific fields
}

빌딩 구현 :

type Movable interface {
  Object
  movable()
}

type MovableImpl struct {
  ObjectImpl // Embedded Object implementation
}

func (m *MovableImpl) movable() {}
유형 Building Struct { embovableimpl // 내장 부동 구현 // 추가 건물 별 필드 }

movable 구현 :

type Movable interface {
  Object
  movable()
}

type MovableImpl struct {
  ObjectImpl // Embedded Object implementation
}

func (m *MovableImpl) movable() {}
유형 movable 인터페이스 { 물체 움직일 수 있는() } 유형 movableimpl struct { ObjectImpl // 내장 객체 구현 } func (m *movableimpl) movable () {}

자동차 구현 :

type Movable interface {
  Object
  movable()
}

type MovableImpl struct {
  ObjectImpl // Embedded Object implementation
}

func (m *MovableImpl) movable() {}
type car struct { MovableImpl // 내장 Movable 구현 // 추가 자동차 별 필드 }

예제 사용법 :

  1. // movable 인터페이스를 구현하지 않기 때문에 movable-typed 변수에 빌드를 할당 할 수 없습니다. Var Movable Movable = Building {} // 그러나 움직일 수없는 구현 객체와 이동식 객체가 모두 객체 유형 변수에 할당 할 수 있습니다. var object 객체 = building {}
  2. 임베딩의 장점 :

How Can Embedding Improve Complex Structural Hierarchy Implementation in Go?

  1. 구현 단순화.
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3