# Fieldnames for a user-defined struct

**URL:** <https://discourse.julialang.org/t/fieldnames-for-a-user-defined-struct/107661>\
**Category:** General Usage\
**Tags:** question\
**Created:** [December 15, 2023, 12:45pm UTC](https://discourse.julialang.org/t/fieldnames-for-a-user-defined-struct/107661 "2023-12-15T12:45:05Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![jiang\_ming\_zhang](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jiang_ming_zhang/32/204063_2.png) [@jiang\_ming\_zhang](https://discourse.julialang.org/u/jiang_ming_zhang)\
**Post date:** [December 15, 2023, 12:45pm UTC](https://discourse.julialang.org/t/fieldnames-for-a-user-defined-struct/107661/1 "2023-12-15T12:45:05Z")

</div>

Suppose I have a variable ‘x’ which is of type ‘mydatatype’ which is a user-defined struct.

When I tried

```julia
fieldnames(x)

```

I got a method error.

Is it because I need a method of ‘fieldnames’ for my self-defined datatype?

---

<div class="post-metadata">

**Author:** ![barucden](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/barucden/32/26154_2.png) [@barucden](https://discourse.julialang.org/u/barucden)\
**Post date:** [December 15, 2023, 12:51pm UTC](https://discourse.julialang.org/t/fieldnames-for-a-user-defined-struct/107661/2 "2023-12-15T12:51:35Z")

</div>

It operates on a `DataType`:

```julia
julia> struct X
         a
         b
       end

julia> fieldnames(X) # X is a type
(:a, :b)

julia> fieldnames(X(1,2)) # X(1, 2) is an object of type X
ERROR: MethodError: no method matching fieldnames(::X)

```

---

<div class="post-metadata">

**Author:** ![mike.ingold](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mike.ingold/32/203749_2.png) [@mike.ingold](https://discourse.julialang.org/u/mike.ingold)\
**Post date:** [December 15, 2023, 2:26pm UTC](https://discourse.julialang.org/t/fieldnames-for-a-user-defined-struct/107661/3 "2023-12-15T14:26:02Z")

</div>

Note that, if you have some `x` and aren’t sure what type to specify for it, you could also `fieldnames(typeof(x))`.

Side note: I wonder if this should be default behavior, e.g. `fieldnames(x::T) where {???} = fieldnames(T)` if it’s possible to declare that `T` is an instance and not a type in itself.

---

<div class="post-metadata">

**Author:** ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)\
**Post date:** [December 15, 2023, 3:03pm UTC](https://discourse.julialang.org/t/fieldnames-for-a-user-defined-struct/107661/4 "2023-12-15T15:03:37Z")

</div>

> [@mike.ingold](#):
>
> if it’s possible to declare that `T` is an instance and not a type in itself.

It is possible to just define

```julia
fieldnames(x) = fieldnames(typeof(x))

```

since it will hit the most specific method that matches. Not recommending this, BTW.
