如何将类型传递给在内部构造函数中调用的函数(等效于 "this")?

How do I pass a type to a function called in the inner constructor ("this" equivalent)?

我有一个在不同结构中运行的函数,如何知道我的函数在哪个结构中运行。 示例:

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 创建的实例来调度 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

如果它在运行时,您通常会以一种或另一种方式使用多重分派,或者传递参数或传递类型(参见其他答案和评论)。

但是,如果它用于调试,您可以使用 stacktrace():

function foo()
   st = stacktrace()[2]
   println("Debug info :", st)
end

现在使用您的结构:

julia> A();
Debug info :A() at REPL[3]:3

julia> B();
Debug info :B() at REPL[12]:3

#EDIT 如果你打算传递一个优雅的高性能解决方案可以是:

function foo(::Type{A})
    @show "typeA"
end

function foo(::Type{B})
    @show "typeB"
end

struct B
    function B()
        foo(B)
        return new()
    end
end

现在:

julia> B();
"typeB" = "typeB"