我有一个在不同结构中运行的函数,如何知道我的函数在哪个结构中运行。 示例:
function foo()
#here I need to find out the name of the struct this function runs (which constructor called it)
in, A or B
end
struct A
arg
function A(arg)
foo(arg)
return new(arg)
end
end
struct B
arg
function B(arg)
foo(arg)
return new(arg)
end
end
最佳答案
在内部构造函数中使用 new
创建的实例来分派(dispatch) foo
。当然,您可以自由自定义 foo
来做更多不同的事情,而不仅仅是打印类型的符号。
foo(t::T) where T = Symbol(T)
struct A
function A()
instance = new()
println("foo was called in ", foo(instance))
return instance
end
end
struct B
function B()
instance = new()
println("foo was called in ", foo(instance))
return instance
end
end
A() # prints: foo was called in A
B() # prints: foo was called in B
关于function - 如何将类型传递给在内部构造函数 ("this"等效项中调用的函数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69339192/