Yves
Yves

Reputation: 12371

Julia: how to use type

struct MyData
    data
    # constructor
    function MyData()
        data = 1
    end
end

myData = MyData()
myData.data #error

I assumed Julia's struct was just like struct in C. So I don't know why I get an error there:

type int64 has no field data

Upvotes: 3

Views: 157

Answers (2)

David P. Sanders
David P. Sanders

Reputation: 5325

Normally you want to use a so-called "outer constructor", i.e. a function of the same name that is defined outside the definition of the type itself. You also want to specify the type of each field as a concrete type, e.g. Int in this example:

struct MyType
    data::Int
end

This has already defined, automatically, a couple of constructors:

x = MyType(3)
x.data

You can define new outer constructors, e.g. to have a default value:

MyType() = MyType(0)  # defines a new constructor

x = MyType()

The kind of constructor you were trying to define is called an "inner constructor" (since it lives inside the type definition). It is used when there is something special that you want to force for each new object. For example, you could make sure that the data must be positive and throw and error if not:

struct MyType2
    data::Int

    function MyType2(x::Int)
        if x <= 0
            throw(ArgumentError("x must be positive"))
        end

        new(x)
    end
end

x = MyType2(3)
y = MyType2(-17)

You should have a look at the documentation on constructors:

http://docs.julialang.org/en/release-0.4/manual/constructors/

Upvotes: 2

Łukasz Daniluk
Łukasz Daniluk

Reputation: 470

Functions in Julia return the last expression in them. In this case, it is data = 1, that is data is returned instead of new instance of MyData. Simply add line with new(data) after data = 1 to return new instance of MyData, and it will work properly.

Upvotes: 5

Related Questions