# Do julia structs have member functions (and this-\>)

**URL:** https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839
**Category:** New to Julia
**Created:** [February 5, 2018, 4:57pm UTC](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839 "2018-02-05T16:57:03Z")
**Posts on this page:** 20
**Page:** 1

<div class="post-metadata">

### Author: ![ivo\_welch](https://avatars.discourse-cdn.com/v4/letter/i/d2c977/32.png) [@ivo\_welch](https://discourse.julialang.org/u/ivo_welch)
#### Post date: [February 5, 2018, 4:57pm UTC](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839/1 "2018-02-05T16:57:03Z")

</div>

I see that structs can have constructors, but can they also contain functions? I tried

```julia
julia> mutable struct b; x::Int64; function y() x=22; end; end

```

which gave no error, but `b.y()` does not work.

---

<div class="post-metadata">

### Author: ![pfitzseb](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/pfitzseb/32/45566_2.png) [@pfitzseb](https://discourse.julialang.org/u/pfitzseb)
#### Post date: [February 5, 2018, 5:23pm UTC](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839/2 "2018-02-05T17:23:00Z")

</div>

Sure, you just can’t initialize them like that:

```julia
julia> struct Foo
         f
       end

julia> F = Foo(x -> 2x)
Foo(#9)

julia> F.f(3)
6

```

For this to be fast you’d want to parametrize `Foo` on the type of `f` though:

```julia
struct Foo{T}
  f::T
end

```

* * *

Just noticed that you probably wanted your `y` to mutate `b.x` or be a static method or something, so the above is probably irrelevant.

---

<div class="post-metadata">

### Author: ![ivo\_welch](https://avatars.discourse-cdn.com/v4/letter/i/d2c977/32.png) [@ivo\_welch](https://discourse.julialang.org/u/ivo_welch)
#### Post date: [February 5, 2018, 5:41pm UTC](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839/3 "2018-02-05T17:41:08Z")

</div>

thanks, pfitzseb. alas, I did not mean just the ability for structs to contain functions. I meant member functions with convenient default access to the contents of the struct (aka, C++ member functions). I can accomplish the same with

```julia
function y(Foo foo)
    foo.x=22
end#function y

## not, as in C++, grouped inside the struct, and with access to member [this->x]
struct Foo
   x::Int64
   function y() x=22; end#function
end#struct

```

so, it is more of a style question, coming from C++.

---

<div class="post-metadata">

### Author: ![foobar\_lv2](https://avatars.discourse-cdn.com/v4/letter/f/ee59a6/32.png) [@foobar\_lv2](https://discourse.julialang.org/u/foobar_lv2)
#### Post date: [February 5, 2018, 5:43pm UTC](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839/4 "2018-02-05T17:43:12Z")

</div>

Short answer: No. You need to pass the `this`-pointer (mutables are de-facto pointers) explicitly, i.e. define  
`function y(some_b::b) some_b.x=22; end;`

If this isn’t about syntactic sugar but name-spaces, consider writing a module where you would otherwise write a class with lots of methods (and then just don’t export the stuff you consider private).

Or will this end up about virtual functions / OOP? Then it is complicated and you need to plan somewhat differently in julia.

Inner constructors are AFAIK really only meant for immutable structs.

edit: Forget about the pointer/mutable/immutable, you always need to pass `this` explicitly, regardless of whether it is mutable or not. `C`-style.

---

<div class="post-metadata">

### Author: ![vvjn](https://avatars.discourse-cdn.com/v4/letter/v/5f9b8f/32.png) [@vvjn](https://discourse.julialang.org/u/vvjn)
#### Post date: [February 5, 2018, 6:30pm UTC](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839/5 "2018-02-05T18:30:41Z")

</div>

You could do the following…

```julia
function Foo()
      x::Int = -1
      setx(x_) = (x = x_) 
      getx() = x
      () -> (getx;setx)
end

f = Foo()
f.getx()
f.setx(22)
f.getx()
f.setx("22") # (fails)
```

---

<div class="post-metadata">

### Author: ![jw3126](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jw3126/32/3086_2.png) [@jw3126](https://discourse.julialang.org/u/jw3126)
#### Post date: [February 5, 2018, 7:15pm UTC](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839/6 "2018-02-05T19:15:51Z")

</div>

@vvjn do you know, whether the fact, that `getx` and `setx` are fields of `f` is just an implementation detail, that may go away at any point, or if this is behaviour that one can rely on?

---

<div class="post-metadata">

### Author: ![vvjn](https://avatars.discourse-cdn.com/v4/letter/v/5f9b8f/32.png) [@vvjn](https://discourse.julialang.org/u/vvjn)
#### Post date: [February 5, 2018, 8:22pm UTC](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839/7 "2018-02-05T20:22:38Z")

</div>

I’m not completely sure but I don’t think this will go away. Besides, in 1.0 you will be able to overload the `.` operator. So, this can be replicated pretty easily by overload `.`.

And btw, this style is not really recommended for julia since it doesn’t look very pretty to most julia people and you can’t perform dispatch on the resulting object.

---

<div class="post-metadata">

### Author: ![Christopher\_Fisher](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/christopher_fisher/32/26132_2.png) [@Christopher\_Fisher](https://discourse.julialang.org/u/Christopher_Fisher)
#### Post date: [February 5, 2018, 8:29pm UTC](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839/8 "2018-02-05T20:29:43Z")

</div>

I came across a similar discussion on [stack overflow](https://stackoverflow.com/questions/39133424/how-to-create-a-single-dispatch-object-oriented-class-in-julia-that-behaves-l) that might be of interest.

---

<div class="post-metadata">

### Author: ![pasha](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/pasha/32/3319_2.png) [@pasha](https://discourse.julialang.org/u/pasha)
#### Post date: [February 5, 2018, 8:33pm UTC](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839/9 "2018-02-05T20:33:10Z")

</div>

My understanding is that object methods are not part of the design, and won’t be in order to preserve the benefits of multiple dispatch. There’s much written on this out there even in the language doc (see [here in Methods for a start)](https://docs.julialang.org/en/stable/manual/methods.html) .

---

<div class="post-metadata">

### Author: ![foobar\_lv2](https://avatars.discourse-cdn.com/v4/letter/f/ee59a6/32.png) [@foobar\_lv2](https://discourse.julialang.org/u/foobar_lv2)
#### Post date: [February 5, 2018, 8:41pm UTC](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839/10 "2018-02-05T20:41:37Z")

</div>

> [@vvjn](#):
>
> You could do the following…

Don’t do this!

```julia
using BenchmarkTools

function Foo()
      x::Int = -1
      setx(x_) = (x = x_) 
      getx() = x
      () -> (getx;setx)
end

f = Foo()

function fob(f, x)
       f.setx(x)
end

mutable struct Foo2
    x::Int64
end

function setx(a::Foo2, v)
 a.x=v
end

foo=Foo2(4)

@btime fob($f, $22)
  72.118 ns
@btime setx($foo, $22)
  2.209 ns

```

Alternatively, read the `@code_native` or `@code_llvm` generated by this abomination to see why it is not nice.

---

<div class="post-metadata">

### Author: ![ivo\_welch](https://avatars.discourse-cdn.com/v4/letter/i/d2c977/32.png) [@ivo\_welch](https://discourse.julialang.org/u/ivo_welch)
#### Post date: [February 5, 2018, 9:08pm UTC](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839/11 "2018-02-05T21:08:09Z")

</div>

the stack overflow example is interesting and unexpected, so let me repeat it:

```julia
julia> function Person(name, age)
        getName() = name
        getAge() = age
        getOlder() = (age+=1)
        ()->(getName;getAge;getOlder)
       end
Person (generic function with 1 method)

julia> o = Person("bob", 26)
(::#3) (generic function with 1 method)

julia> o.getName()
"bob"

julia> o.getAge()
26

julia> o.getOlder()
27

julia> o.getAge()
27

```

as to my original question, I am perfectly happy with julia’s way of doing things, so no object-orientation ala C++ or Java. I just wanted to be sure that I am using julia as intended.

---

<div class="post-metadata">

### Author: ![vvjn](https://avatars.discourse-cdn.com/v4/letter/v/5f9b8f/32.png) [@vvjn](https://discourse.julialang.org/u/vvjn)
#### Post date: [February 6, 2018, 4:22pm UTC](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839/12 "2018-02-06T16:22:05Z")

</div>

Got curious, and it looks like f.setx is faster than python method calling.

```julia
class Foo:
    def __init__ (self):
        self.x = -1

    def setx(self, x_):
        self.x = x_
        
if __name__ == ' __main__':
    import timeit
    n = 10000000
    t = timeit.timeit("f.setx(22)", setup="from __main__ import Foo; f = Foo()", number=n)
    print(str((t/n)/1e-9) + " ns")
```

Above gives me around 100ns, while running `@btime fob($f, $22)` from your code gives me around 40ns.

---

<div class="post-metadata">

### Author: ![ExpandingMan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/expandingman/32/866_2.png) [@ExpandingMan](https://discourse.julialang.org/u/ExpandingMan)
#### Post date: [February 6, 2018, 6:44pm UTC](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839/13 "2018-02-06T18:44:56Z")

</div>

I strongly suggest you read [this](https://en.wikipedia.org/wiki/Multiple_dispatch) and [this](https://docs.julialang.org/en/stable/manual/methods/) before designing anything that contains `struct`s with functions as members. Multiple dispatch is a beautiful paradigm for writing code, it’s definitely worth getting familiar with it and how Julia instantiates it. I came to Julia for the performance, but it’s probably this more than anything else that keeps me not wanting to ever use another language. Sometimes it make sense to have functions as `struct` members even within the paradigm of multiple dispatch, but usually it doesn’t.

---

<div class="post-metadata">

### Author: ![pasha](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/pasha/32/3319_2.png) [@pasha](https://discourse.julialang.org/u/pasha)
#### Post date: [February 6, 2018, 9:37pm UTC](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839/14 "2018-02-06T21:37:13Z")

</div>

Also bear in mind that Julia 0.7 [is slated](https://github.com/JuliaLang/julia/issues/1974) to have simple get/set accessors for struct fields. So, there is little point in writing lots of those.

Mainly I second @ExpandingMan - each language will have slightly different usage patterns, and Multiple Dispatch is amazing in use.

---

<div class="post-metadata">

### Author: ![vvjn](https://avatars.discourse-cdn.com/v4/letter/v/5f9b8f/32.png) [@vvjn](https://discourse.julialang.org/u/vvjn)
#### Post date: [February 7, 2018, 3:12am UTC](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839/15 "2018-02-07T03:12:19Z")

</div>

You could also do this…

```julia
      type Foo
         x::Int
         setx
         getx
         function Foo(x)
           f = new(x)
           f.setx = (x_) -> (f.x = x_)
           f.getx = () -> f.x
           f
         end
       end
```

`setx` and `getx` are still slow but faster than the function one, though `x` is modifiable now.

---

<div class="post-metadata">

### Author: ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)
#### Post date: [February 7, 2018, 11:59am UTC](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839/16 "2018-02-07T11:59:08Z")

</div>

In 0.7, this will be:

```julia
mutable struct Foo
    x::Int
end

function Base.setproperty!(f::Foo, v, s::Symbol)
    if s == :x
        f.x = v
    else
        error("unknown property $s")
    end
end

function Base.getproperty(f::Foo, s::Symbol)
    if s == :x
        return f.x
    else
        error("unknown property $s")
    end
end

```

And will have no performance penalty.

---

<div class="post-metadata">

### Author: ![ExpandingMan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/expandingman/32/866_2.png) [@ExpandingMan](https://discourse.julialang.org/u/ExpandingMan)
#### Post date: [February 7, 2018, 3:56pm UTC](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839/17 "2018-02-07T15:56:09Z")

</div>

> [@kristoffer.carlsson](#):
>
> And will have no performance penalty.

I’m curious, this would seem to imply that Julia runs the `setproperty!` and `getproperty` functions at compile time. Otherwise, there certainly would be a performance penalty because running `getproperty` at run-time and checking a conditional structure would certainly be slower than simply accessing a field.

Is that indeed what happens, `getproperty` and `setproperty!` will run at compile time?

---

<div class="post-metadata">

### Author: ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)
#### Post date: [February 7, 2018, 4:07pm UTC](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839/18 "2018-02-07T16:07:17Z")

</div>

The functions themselves can’t be run at compile time (you won’t know what e.g. `f.x` is when you compile) but all the branches and stuff will be gotten rid of since the symbol is a constant, and 0.7 have new fancy constant propagations spanning function boundaries.

---

<div class="post-metadata">

### Author: ![josimar](https://avatars.discourse-cdn.com/v4/letter/j/cab0a1/32.png) [@josimar](https://discourse.julialang.org/u/josimar)
#### Post date: [August 12, 2019, 7:29pm UTC](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839/19 "2019-08-12T19:29:22Z")

</div>

Hi, could you update the link for your second reference were it is says “this” (101) ? It appears the link is broken. thanks in advance !

---

<div class="post-metadata">

### Author: ![ExpandingMan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/expandingman/32/866_2.png) [@ExpandingMan](https://discourse.julialang.org/u/ExpandingMan)
#### Post date: [August 12, 2019, 8:00pm UTC](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839/20 "2019-08-12T20:00:20Z")

</div>

It seems discourse removes the ability to edit very old posts. [Here](https://docs.julialang.org/en/v1.1/manual/methods/) is the updated url to the Julia manual section on methods.

[Next page](https://discourse.julialang.org/t/do-julia-structs-have-member-functions-and-this/8839.md?page=2)
