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

标签 function julia this

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

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/

相关文章:

javascript - 在Javascript中调用匿名函数中的函数时如何使用 "this"关键字?

javascript - 如何用 .on() 方法替换 .live() 方法

基于 Python 类的装饰器,带有可以装饰方法或函数的参数

dictionary - 嵌套字典中无意义的MethodError?

julia - Julia 中缺少、无、未定义和 NaN 之间的用法和约定差异

javascript - 我可以使用 "this"访问范围对象本身的属性吗?

javascript - 使用 javascript 在 html 中调用外部函数时出现问题

javascript - 如何在没有任何事件的情况下在jsp中调用javascript函数

julia - 如何在 Julia 中读取记录格式 json?

matlab - 在 MATLAB 中是否有 'self' 来引用自己的结构?