Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom methods in a struct is not possible in Julia #4

Open
SMMousaviSP opened this issue Feb 20, 2023 · 0 comments
Open

Custom methods in a struct is not possible in Julia #4

SMMousaviSP opened this issue Feb 20, 2023 · 0 comments

Comments

@SMMousaviSP
Copy link

An example is given that it is possible to have a custom method inside a struct like this:

struct Person
    name::String
    age::Int
    occupation::String
    
    function Person(name::String, age::Int, occupation::String)
        new(name, age, occupation)
    end
    
    function introduce(p::Person)
        println("Hi, my name is $(p.name) and I am a $(p.age)-year-old $(p.occupation).")
    end
end

p1 = Person("Alice", 25, "Software Engineer")
p1.introduce()

However, this code will not run and it should be changed to this:

struct Person
    name::String
    age::Int
    occupation::String
    
    function Person(name::String, age::Int, occupation::String)
        new(name, age, occupation)
    end
end

function introduce(p::Person)
    println("Hi, my name is $(p.name) and I am a $(p.age)-year-old $(p.occupation).")
end

p1 = Person("Alice", 25, "Software Engineer")
introduce(p1)

As far as I understood, after correcting the code, the introduce function is just a normal function and not a custom method of struct Person.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant