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

비밀번호

댓글 작성자
 




... 121  122  123  124  [125]  126  127  128  129  130  131  132  133  134  135  ...
NoWriterDateCnt.TitleFile(s)
10797정성태5/23/201521622VC++: 91. 자식 스레드에 자동 상속되는 TEB의 SubProcessTag 필드파일 다운로드1
10796정성태5/23/201532456오류 유형: 293. SQL Server Management Studio 실행 시 "Cannot find one or more components" 오류
10795정성태5/23/201530585오류 유형: 292. InstallUtil로 .NET 서비스 등록 시 오류 - Operation is not supported. (Exception from HRESULT: 0x80131515). [3]
10794정성태5/22/201525545개발 환경 구성: 267. (무료) 마이크로소프트 온라인 강좌 소개 - 네트워킹 기초 [1]
2925정성태5/14/201525124디버깅 기술: 73. PDB 기호 파일의 경로 구성 방식파일 다운로드1
2924정성태5/14/201528434VS.NET IDE: 100. 비주얼 스튜디오 원격 디버깅 시 'Unknown function' 콜스택이 나온다면?
2923정성태5/12/201587776기타: 52. 도서: 시작하세요! C# 6.0 프로그래밍: 기본 문법부터 실전 예제까지 [17]
2922정성태5/12/201524646오류 유형: 291. ssindex.cmd 실행 시 '...[tfs_collection_url]...' not found in srcsrv.ini 오류 발생
2921정성태5/9/201530984개발 환경 구성: 266. 인텔에서 구현한 최대 절전 모드 기능 - Intel® Rapid Start Technology
2920정성태5/9/201522128오류 유형: 290. 디스크 관리자의 파티션 축소 시, There is not enough space available on the disk(s) to complete this operation.
2919정성태5/9/201522006오류 유형: 289. Error: this template attempted to load component assembly 'NuGet.VisualStudio.Interop, ...'
2918정성태5/9/201540541Windows: 111. 복구(Recovery) 파티션 삭제하는 방법 [3]
2917정성태5/9/201530966오류 유형: 288. .NET Framework 4.6이 설치된 경우 "Intel® Rapid Storage Technology (Intel® RST) RAID Driver"가 설치 안 되는 문제 [5]
2916정성태5/9/201532031오류 유형: 287. 레지스트리 권한 오류 - Cannot edit [Registry key name]: Error writing the value's new contents.
2915정성태5/9/201531149개발 환경 구성: 265. TrustedInstaller 권한으로 프로그램 실행시키는 방법 [11]
2914정성태5/9/201528490DDK: 7. 정식 인증서가 있는 경우 Device Driver 서명하는 방법 [2]
2913정성태4/30/201526256.NET Framework: 511. Build 2015 행사에서 소개된 (맥/리눅스/윈도우 용 무료) Visual Studio Code 개발 도구 [8]
2912정성태4/29/201521986오류 유형: 286. VirtualBox에 Windows 8/2012 설치 시 "Error Code: 0x000000C4" 오류 발생
2911정성태4/29/201520617오류 유형: 285. Visual Studio 2015를 제거한 경우 Microsoft.VisualStudio.Web.PageInspector.Loader 어셈블리를 못 찾는 문제 [2]
2910정성태4/29/201524488오류 유형: 284. System.TypeLoadException: Could not load type 'System.Reflection.AssemblySignatureKeyAttribute' from assembly [1]
2909정성태4/29/201520620오류 유형: 283. WCF 연결 오류 - Expected record type 'PreambleAck'
2908정성태4/29/201528914오류 유형: 282. 원격에서 SQL 서버는 연결되지만, SQL Express는 연결되지 않는 경우
2907정성태4/29/201518990.NET Framework: 510. 제네릭(Generic) 인자에 대한 메타데이터 등록 확인
2906정성태4/28/201521603오류 유형: 281. DebugView로 인한 System.Diagnostics.Trace.WriteLine 멈춤(Hang) 현상
2905정성태4/27/201521948오류 유형: 280. HttpResponse.Headers.Add에서 "System.PlatformNotSupportedException: This operation requires IIS integrated pipeline mode." 예외 발생
2904정성태4/27/201527204DDK: 6. ZwTerminateProcess로 프로세스를 종료하는 Device Driver 프로그램 [2]파일 다운로드1
... 121  122  123  124  [125]  126  127  128  129  130  131  132  133  134  135  ...