Type, Structure

I want to create Structure to store my details

struct MyStruct

        name:: String
        age ::int 
        Father_Name:: String
end  

data= Array{MyStruct,1}("anil",22,"Mathew) 

Then, I want to use MyStruct Type in an Array

Unfortunately, it’s wrong, how to code

Your code has several syntax errors (Int, closing quote in "Mathew"), but apart from that, you still have to use the explicit constructor to create an instance of MyStruct, which you can put in a vector. Eg

struct MyStruct
    name::String
    age::Int 
    Father_Name::String
end  

data = [MyStruct("anil", 22, "Mathew")]

see the manual:
https://docs.julialang.org/en/v1/manual/types/#Composite-Types-1

2 Likes

Thank you for your answer.
First of all,I am not programmer,I believe, i could not make that Array, because, julia is multi dispatching, when i create array, julia will check function with type argument and since mystructure is not pre defined, julia will not match the function. Am i right?
Then, i have read the topic, unfortunately, i didnt understand anything. Could you please explain with Examples.
Moreover, “not all types can have a respective object
(instances of that type)” .Please explain this also with examples.

I don’t think so. I am not sure I understand what you are saying here though.

If you want to program (any language, not specifically Julia), I think you should invest the time in learning the basics. I still think that working through the manual from the beginning is the best option, but there are some books here:

https://julialang.org/learning/

to fix based on your code, the minimal modification is:

julia> Array{MyStruct,1}([MyStruct("great",2,"nice")])
1-element Array{MyStruct,1}:
 MyStruct("great", 2, "nice")

The reason is that the Array{T,N} constructor wants the argument to be an array with eltype being T, I understand this is not the easiest code to write, so I wonder if there’s better way.

But, I noticed you can ‘hack’ the Base.convert a little:

julia> Base.convert(MyStruct, x::AbstractArray) = MyStruct(x...)

julia> Array{MyStruct,1}([["great",2,"nice"], ["hmm", 3, "hacky"]])
2-element Array{MyStruct,1}:
 MyStruct("great", 2, "nice")
 MyStruct("hmm", 3, "hacky")

which, at this point you might as well just write:

MyStruct(x::Tuple) = new(x...) #inner constructor inside `struct`

julia> MyStruct.([("great",2,"nice"), ("hmm", 3, "hacky")])
2-element Array{MyStruct,1}:
 MyStruct("great", 2, "nice")
 MyStruct("hmm", 3, "hacky")