Getting default value for certain DataType in Julia

Viewed 54

Is there any way to get default value having DataType?

By "default" I mean something similar to Golang:

var message string
// Default value: ""

var age int
// Default value: 0

var isValid bool
// Default value: false

I was trying to do it in Julia in a same way:

function get_default_value(t::DataType)
    x::t
    return x
end

function main()
    println(get_default_value(Integer))
end

main()

but got UndefVarError: x not defined.

Any ideas how to do this?

1 Answers

One misconception that I want to clarify first is that x::Int is not defining a new Int variable called x, it's an assertion that the value x contains is of Int type. That line is not creating a new variable called x.

Also, variables themselves don't usually have an inherent type in Julia, and so you can't have default values for variables. (There are a couple of ways to declare a variable as holding only values of a particular type, but even those only declare the variable names, without defining them into existence; and so, there's no default values there either.)

The functions I've mentioned below operate on types, and are defining 'additive identity' and 'multiplicative identity' rather than a default value. When other languages give a default value to their variables, they usually tend to use the additive identity of that type, so it works out that zero fills in that role in most cases.

So, to get results similar to the ones you've mentioned, zero works for numeric types, Date types, etc.

julia> zero(Dates.Time)
0 nanoseconds

julia> zero(Bool)
false

julia> zero(Int)
0

julia> zero(Float64)
0.0

zero isn't defined for String type though, for that you use the one method:

julia> one(String)
""

julia> one(Int)
1

julia> one(Bool)
true

The reason is that string concatenation in Julia is done with the * operator, and one is the function in Julia that returns the identity ("default") value for *.

There's also the oneunit function that's useful in certain scenarios.

Related