Julia syntax error @kwdef with default value as string

35 views Asked by At

This code produce a syntax error. I cannot use a default value in a @kwdef struct?

@kwdef struct MyStruct
    indir::String = "./",
    outdir::String = "./result",
    threshold::Int = 2
end


ERROR: syntax: invalid assignment location ""./result"" around REPL[16]:1
1

There are 1 answers

0
Jonathan F. On BEST ANSWER

The @kwdef is a macro in julia that defines a struct, and automatically creates an associated constructor.

Normally, to create a struct and constructor, one would write:

struct Foo
    paramWithoutDefaultVal::String
    paramWithDefaultVal::String
end
Foo(paramWithoutDefaultVal; paramWithDefaultVal="Default Text") = Foo(paramWithoutDefaultVal, paramWithDefaultVal)

julia> Foo("Specified Text")

       Foo("Specified Text", "Default Text")

julia> Foo("Specified Text", "Also Specified Text")

       Foo("Specified Text", "Also Specified Text")

But the macro @kwdef increases readability by simplifying this slightly.

The same struct and constructor can be defined, using @kwdef with:

@kwdef struct Bar
    paramWithoutDefaultVal::String
    paramWithDefaultVal::String = "Default Text"
end

julia> Bar("Specified Text")

       Bar("Specified Text", "Default Text")

julia> Bar("Specified Text", "Also Specified Text")

       Bar("Specified Text", "Also Specified Text")

Note: In both examples, there are no commas between parameters. The code provided in the question was breaking due to the commas being included. @kwdef uses the same syntax as a struct definition, so it should not have commas.