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

비밀번호

댓글 작성자
 




... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12412정성태11/16/202020662.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/202017442오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/202017586디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202019428.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202034676도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202019775.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202020764.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202018630.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202019253.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202018162.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202019667.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202018917VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/202015135오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202018662.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/202018180오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/202018199.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/202015221VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/202018001오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/202015623오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/202015289오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202019829.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202019481디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
12389정성태11/1/202018637.NET Framework: 958. C# 9.0 - (8) 정적 익명 함수 (static anonymous functions)파일 다운로드1
12388정성태10/29/202017676오류 유형: 674. 어느 순간부터 닷넷 응용 프로그램 실행 시 System.Configuration.ConfigurationErrorsException 예외가 발생한다면?
12387정성태10/28/202018464.NET Framework: 957. C# - static 필드의 정보가 GC Heap에 저장될까요? [3]파일 다운로드1
12386정성태10/28/202019207Linux: 34. 사용자 정보를 함께 출력하는 리눅스의 ps 명령어 사용 방법
... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...