go/test/reflectmethod2.go
David Crawshaw cc158403d6 cmd/compile: track reflect.Type.Method in deadcode
In addition to reflect.Value.Call, exported methods can be invoked
by the Func value in the reflect.Method struct. This CL has the
compiler track what functions get access to a legitimate reflect.Method
struct by looking for interface calls to either of:

	Method(int) reflect.Method
	MethodByName(string) (reflect.Method, bool)

This is a little overly conservative. If a user implements a type
with one of these methods without using the underlying calls on
reflect.Type, the linker will assume the worst and include all
exported methods. But it's cheap.

No change to any of the binary sizes reported in cl/20483.

For #14740

Change-Id: Ie17786395d0453ce0384d8b240ecb043b7726137
Reviewed-on: https://go-review.googlesource.com/20489
Reviewed-by: Matthew Dempsky <mdempsky@google.com>
2016-03-11 21:19:20 +00:00

36 lines
719 B
Go

// run
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The linker can prune methods that are not directly called or
// assigned to interfaces, but only if reflect.Type.MethodByName is
// never used. Test it here.
package main
import reflect1 "reflect"
var called = false
type M int
func (m M) UniqueMethodName() {
called = true
}
var v M
type MyType interface {
MethodByName(string) (reflect1.Method, bool)
}
func main() {
var t MyType = reflect1.TypeOf(v)
m, _ := t.MethodByName("UniqueMethodName")
m.Func.Interface().(func(M))(v)
if !called {
panic("UniqueMethodName not called")
}
}