1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

概要

paiza.ioでelixirやってみた。
defstruct再考。

サンプルコード

defmodule Point do
	defstruct x: 0, y: 0
	def add(%Point{x: x, y: y}, %Point{x: other_x, y: other_y}) do
		%Point{
		    x: x + other_x, 
		    y: y + other_y
		}
	end
end
defmodule Main do
    require Point
    p1 = %Point{
	    x: 1, 
	    y: 2
	}
	p2 = %Point{
	    x: 3, 
	    y: 4
	}
	IO.inspect Point.add(p1, p2)
end

defmodule Person do
	defstruct name: 'unknown', age: 0
end
defmodule Hoge do
	require Person
	def hoge do
		default_person = %Person{}
		tanaka = %Person{
		    name: 'tanaka', 
		    age: 24
		}
		Hoge.print_person(default_person)
		Hoge.print_person(tanaka)
	end
	def print_person(person) do
		IO.inspect person
		IO.puts person.name
		IO.inspect person.age
	end
end
Hoge.hoge

defmodule User do
	defstruct [:name, :age]
end
defmodule Main do
	require User
	alice = %User{
	    name: "Alice", 
	    age: 20
	}
	IO.inspect alice.name
end


実行結果

%Point{x: 4, y: 6}
%Person{age: 0, name: 'unknown'}
unknown
0
%Person{age: 24, name: 'tanaka'}
tanaka
24
"Alice"

成果物

以上。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?