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

Time:09-27

I have a function that runs inside different structs, how to know in which struct that my function runs in. Example:

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

CodePudding user response:

Use the instance created by new in your inner constructor to dispatch foo. Of course, you are free to customize foo to do much more varying things than just print the symbol of the type.

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

CodePudding user response:

If it is in runtime you normally would use multiple dispatch in one way or another or pass the argument or pass the type (see other answers and comments).

However, if it is for debugging you could use stacktrace():

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

And now using your structs:

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

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

#EDIT if you plan to pass type an elegant high-performance solution could be:

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

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

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

And now:

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