golang 구조체가 특정 인터페이스를 구현했는지 확인하기


  • go 에서 특정 인터페이스를 내가 만든 구조체가 구현하고있는지 확인하려면 이렇게 하면된다.

    pacakge main
    
    var (
      _ InterfaceToImplementA = (*StructThatImplABC)(nil)
      _ InterfaceToImplementB = (*StructThatImplABC)(nil)
      _ InterfaceToImplementC = (*StructThatImplABC)(nil)
    )
    
    type InterfaceToImplementA interface {
      Foo(string) string
    }
    
    type InterfaceToImplementB interface {
      Bar(string) error
    }
    
    type InterfaceToImplementC interface {
      DoSomething() error
    }
    
    type StructThatImplABC struct{}
    
    
    // Foo implements interface InterfaceToImplementA
    func (s StructThatImplABC) Foo(string) string {
      return ""
    }
    
    // Bar implements interface InterfaceToImplementB
    func (s StructThatImplABC) Bar(string) error {
      return nil
    }
    
    // DoSomething implements interface InterfaceToImplementC
    func (s StructThatImplABC) DoSomething() error {
      return nil
    }
    
  • 제일 위의 var (...) 구문을 통해서 각 인터페이스를 StructThatImplABC 구조체가 구현하고있는지 확인할 수 있게 된다.

  • 먼저 (*StructThtImplABC)(nil) 은 StructThatImplABC 구조체를 zero-value 포인터에 할당한다. 단순히 체크용도인데 메모리를 쓰기에는 아깝기 때문이다.

  • 그 다음 그 포인터를 각 인터페이스를 구현했다고 표기해주는데, 만약 내가 구현한 코드가 표기된 인터페이스를 제데로 구현하지 못했다면, go는 컴파일 단계에서 에러를 뱉어준다. (아마 ide를 사용하면 ide가 뱉어주겠지)

  • 무튼 이렇게 해서 내가 만든 구조체가 제데로 인터페이스를 구현하고 있는지를 컴파일 전에 확인할 수 있게 된다.