Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

Golang - 구조체의 slice 필드를 Reflection을 이용해 변경하는 방법

우선, 입문부터 해볼까요? ^^ 간단하게 slice를 만들고 이것에 요소를 추가하는 경우 이런 식으로 코딩할 수 있습니다.

buf := make([]string, 0)
buf := append(buf, "test")

위에서 "append"하는 과정을 Reflection으로 구현한다면 reflect를 이용해 유사한 방식으로 처리하게 됩니다.

value := reflect.ValueOf(&buf)
value := reflect.Append(value.Elem(), reflect.ValueOf("test"))

// 만약 포인터로 전달하지 않으면 reflect.Append 호출에서 예외 발생 - reflect: call of reflect.Value.Elem on slice Value
// value := reflect.ValueOf(buf)

보는 바와 같이, slice가 append를 이용할 때도 그 반환값을 다시 buf 변수에 할당해야만 했던 것처럼, reflect를 이용하는 것도 그와 유사한 것입니다. 바로 이런 점 때문에 결국 buf 변수와 reflect.Append가 반환한 value 변수는 같은 상태를 가리키지 않습니다. 즉, 위와 같은 처리가 원본 변수인 buf에 영향을 주는 것은 아닙니다.

fmt.Printf("%v, %v", len(buf), value)
/* 출력 결과
0, [test]
*/

따라서, reflection으로 처리한 결과를 다시 원본 변수인 buf에 대입하려면 다음과 같은 식의 코딩을 통해 reflect.Value로부터 값을 변환해 줘야 합니다.

buf = value.Interface().([]string)
fmt.Printf("%v, %v\n", len(buf), buf[0]) 
/* 출력 결과
0, test
*/




자, 그럼 타입의 멤버로 slice가 있다면 어떻게 될까요?

type MyType struct {
    Buf []string
}

기본적인 코드는 다음과 같이 시작할 수 있습니다.

t := MyType{}
t.Buf = make([]string, 0)

tValue := reflect.ValueOf(t)

bufValue := tValue.FieldByName("Buf") // 필드 이름으로 조회

bufType := bufValue.Type()
fmt.Printf("%v, %v\n", bufType, bufValue)

fmt.Printf("%v\n", bufType.Elem().Kind())

/* 출력 결과
[]string, []
string
*/

그럼 마찬가지로 slice에 멤버를 추가하는 것도 동일하게 반영할 수 있고,

bufValue = reflect.Append(bufValue, reflect.ValueOf("test"))
fmt.Printf("%v, %v", len(t.Buf), bufValue)
/* 출력 결과
0, [test]
*/

원본에 적용하는 것도 상황이 허락된다면 이렇게 할 수 있습니다.

bufValue = reflect.Append(bufValue, reflect.ValueOf("test"))
t.Buf = bufValue.Interface().([]string)
fmt.Printf("%v, %v", len(t.Buf), t.Buf[0])
/* 출력 결과
1, test
*/

그런데, 여기서 문제가 있습니다. 대개의 경우 reflection을 사용할 때는 대상 인스턴스를 interface {}로 받게 될 것입니다.

t := MyType{}
t.buf = make([]string, 0)

Modify(t)

func Modify(inst interface {}) {
     // ... reflection ...
}

위와 같은 상황에서, slice가 아닌 다른 타입이었다면 reflect.Value의 SetString, SetInt 등을 이용해 값을 설정하는 것이 가능합니다. 그런데, slice 유형이라면 단순히 Set 함수를 이용하는 경우 예외가 발생합니다.

changed := reflect.Append(bufValue, reflect.ValueOf("test"))
bufValue.Set(changed) // 예외 발생:  reflect: reflect.Value.Set using unaddressable value

다행히 예외 메시지에 답이 있는데요, 애당초 구조체 인스턴스를 포인터로 전달했어야 하고, reflection을 하려는 측에서도 Pointer인 경우 reflect.ValueOf/TypeOf를 했던 대상의 원본에 대해 한 번 더 Elem()을 호출해 대상 인스턴스를 가져와야 합니다. 아래의 코드는 그 상황을 보여줍니다.

func main() {
    t := MyType{}
    t.Buf = make([]string, 0)

    Modify(&t);

    /* 또는,
    t := &MyType{}
    t.Buf = make([]string, 0)

    Modify(t);
    */
}

func Modify(t interface{}) {

    tType := reflect.TypeOf(t)
    tValue := reflect.ValueOf(t)

    if tType.Kind() == reflect.Ptr {
        tType = tType.Elem()
        tValue = tValue.Elem()
    }

    bufValue := tValue.FieldByName("Buf")

    bufType := bufValue.Type()
    changed := reflect.Append(bufValue, reflect.ValueOf("test"))

    bufValue.Set(changed)
}




만약 타입의 멤버 이름을 소문자로 바꿔 접근성을 변경하면,

type MyType struct {
    buf []string
}

reflect.Append 코드에서 예외가 발생합니다.

// 예외 발생: reflect: reflect.Copy using value obtained using unexported field
bufValue = reflect.Append(bufValue, reflect.ValueOf("test"))

다른 언어와는 달리, reflection으로도 private 필드에 대한 접근은 할 수 없는 것입니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 8/23/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 46  [47]  48  49  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12762정성태8/8/202119379Java: 28. IntelliJ - Unable to open debugger port 오류
12761정성태8/8/202116060Java: 27. IntelliJ - java: package javax.inject does not exist [2]
12760정성태8/8/202112829개발 환경 구성: 594. 전용 "Command Prompt for ..." 단축 아이콘 만들기
12759정성태8/8/202117451Java: 26. IntelliJ + Spring Framework + 새로운 Controller 추가 [2]파일 다운로드1
12758정성태8/7/202116845오류 유형: 751. Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode)
12757정성태8/7/202117462Java: 25. IntelliJ + Spring Framework 프로젝트 생성
12756정성태8/6/202115728.NET Framework: 1084. C# - .NET Core Web API 단위 테스트 방법 [1]파일 다운로드1
12755정성태8/5/202115754개발 환경 구성: 593. MSTest - 단위 테스트에 static/instance 유형의 private 멤버 접근 방법파일 다운로드1
12754정성태8/5/202116147오류 유형: 750. manage.py - Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
12753정성태8/5/202117092오류 유형: 749. PyCharm - Error: Django is not importable in this environment
12752정성태8/4/202113951개발 환경 구성: 592. JetBrains의 IDE(예를 들어, PyCharm)에서 Visual Studio 키보드 매핑 적용
12751정성태8/4/202116872개발 환경 구성: 591. Windows 10 WSL2 환경에서 docker-compose 빌드하는 방법
12750정성태8/3/202113906디버깅 기술: 181. windbg - 콜 스택의 "Call Site" 오프셋 값이 가리키는 위치
12749정성태8/2/202113327개발 환경 구성: 590. Visual Studio 2017부터 단위 테스트에 DataRow 특성 지원
12748정성태8/2/202114341개발 환경 구성: 589. Azure Active Directory - tenant의 관리자(admin) 계정 로그인 방법
12747정성태8/1/202114603오류 유형: 748. 오류 기록 - MICROSOFT GRAPH – HOW TO IMPLEMENT IAUTHENTICATIONPROVIDER파일 다운로드1
12746정성태7/31/202119039개발 환경 구성: 588. 네트워크 장비 환경을 시뮬레이션하는 Packet Tracer 프로그램 소개
12745정성태7/31/202114886개발 환경 구성: 587. Azure Active Directory - tenant의 관리자 계정 로그인 방법
12744정성태7/30/202115270개발 환경 구성: 586. Azure Active Directory에 연결된 App 목록을 확인하는 방법?
12743정성태7/30/202116505.NET Framework: 1083. Azure Active Directory - 외부 Token Cache 저장소를 사용하는 방법파일 다운로드1
12742정성태7/30/202114524개발 환경 구성: 585. Azure AD 인증을 위한 사용자 인증 유형
12741정성태7/29/202116021.NET Framework: 1082. Azure Active Directory - Microsoft Graph API 호출 방법파일 다운로드1
12740정성태7/29/202114519오류 유형: 747. SharePoint - InvalidOperationException 0x80131509
12739정성태7/28/202114950오류 유형: 746. Azure Active Directory - IDW10106: The 'ClientId' option must be provided.
12738정성태7/28/202115898오류 유형: 745. Azure Active Directory - Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).
12737정성태7/28/202114982오류 유형: 744. Azure Active Directory - The resource principal named api://...[client_id]... was not found in the tenant
... 46  [47]  48  49  50  51  52  53  54  55  56  57  58  59  60  ...