AVA
AVA

Reputation: 2558

How can I create a struct in julia?

I am trying to create a structure, txn:

a)

struct txn
    txn_id::Int64
    bank::Char[20]
    branch::Char[20]
    teller::Char[20]
    customer::Char[20]
    account::Char[34]
    timestamp::DateTime
    dr_cr::Char[2]
    amount::Int64
end

gives

Error: TypeError: in txn, in type definition, expected Type, got Array{Char, 1}

b)

struct txn
    txn_id::Int64
    bank::Char(20)
    branch::Char(20)
    teller::Char(20)
    customer::Char(20)
    account::Char(34)
    timestamp::DateTime
    dr_cr::Char(2)
    amount::Int64
end

gives

Error: TypeError: in txn, in type definition, expected Type, got Char

How can I create the struct in Julia?

Upvotes: 1

Views: 2263

Answers (1)

Cameron Bieganek
Cameron Bieganek

Reputation: 7654

In Julia, an array of Chars is not equivalent to a String. The syntax Char(80) creates a single character:

julia> Char(80)
'P': ASCII/Unicode U+0050 (category Lu: Letter, uppercase)

And the syntax Char[80, 81, 82] creates an array of Chars:

julia> Char[80, 81, 82]
3-element Array{Char,1}:
 'P'
 'Q'
 'R'

We can see that an array of characters is not equivalent to a string (note that characters can also be represented using single quotes):

julia> ['a', 'b', 'c'] == "abc"
false

Try defining the string fields in your struct using the String type:

julia> struct Person
           name::String
       end

julia> p = Person("Bob")
Person("Bob")

Upvotes: 4

Related Questions