dongna2498 2014-10-18 20:54
浏览 19
已采纳

如何动态遍历一个包?

This is my first week with Go, so please forgive the ignorance ;). I come in peace from Python. I am building a simple calculator with Addition and Subtraction currently.

My addition.go file looks like this:

package calculator

type Add struct{}

func (h Add) First(x int) int {
    x += 5
    return x
}

func (h Add) Second(x int) int {
    x += 10
    return x
}

The layout of my subtraction.go file looks very similar to addition.go and future features like multiplication.go and division.go will look similar. To run these I have:

package main

import (
    "fmt"
    "github.com/mytester/calculator"
)

type Calc interface {
    First(x int) int
    Second(x int) int
}

func main() {
    x := 10
    var i Calc
    a := &calculator.Add{}
    i = a
    i.First(x)
    fmt.Println(x)
    fmt.Println(i.First(x))
    fmt.Println(i.Second(x))

    fmt.Println("Next method...")
    b := &calculator.Sub{}
    i = b
    fmt.Println(x)
    fmt.Println(i.First(x))
    fmt.Println(i.Second(x))

    // iterate through the rest of my calculator methods

}

This seems very verbose, especially as I add more and more features like multiplication, etc. Is there a way to find all the methods of my calculator & then iterate over all of them? I've looked through the reflect documentation but there doesn't seem to be a way to get this. The order in which they are run doesn't matter....eg subtraction can run before addition.

  • 写回答

1条回答 默认 最新

  • dongtang6775 2014-10-18 22:32
    关注

    Go does not provide the feature you want. There is no mechanism to introspect the contents of packages. The reason for this is that the compiler keeps only functions and variable in the executable that are referenced somewhere. If you never explicitly use a function, it won't be in the executable. Iterating over a possibly incomplete set of symbols is pointless and is therefore not implemented.

    You could make an array containing objects of the types you want to operate on and iterate on that if that solves your problem.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Pytorch深度学习服务器跑不通问题解决?
  • ¥15 部分客户订单定位有误的问题
  • ¥15 如何在maya程序中利用python编写领子和褶裥的模型的方法
  • ¥15 Linux权限管理相关操作(求解答)
  • ¥15 Bug traq 数据包 大概什么价
  • ¥15 在anaconda上pytorch和paddle paddle下载报错
  • ¥25 自动填写QQ腾讯文档收集表
  • ¥15 DbVisualizer Pro 12.0.7 sql commander光标错位 显示位置与实际不符
  • ¥15 android 打包报错
  • ¥15 关于stm32的问题