Common Programming Concepts in Rust
Summary
TLDRこの動画はRustプログラミング言語についての教育チャンネル「Let's Get Rusty」の第3回目の動画です。ホストのBogdanは、基本的なプログラミング概念を紹介しています。変数の不変性と可変性、定数、型注釈、シャドウイング、スカラー型と複合型のデータ型、関数の定義と呼び出し、制御フローの構造(if文、ループ)、そしてコメントの使い方について学ぶことができます。特に、Rustにおける変数の不変性と定数の違い、配列の固定長性、関数の戻り値の指定方法、if-else文の使い方、そしてループの種類について詳しく解説しています。この動画はRustを学びたい人にとって、非常に役立つ内容となっています。
Takeaways
- 📌 Rust は変数の不変性をデフォルトでサポートしています。
- 🔄 変数を再代入するには、`let` キーワードの後に `mut` を追加する必要があります。
- 🔒 `const` キーワードを使用して定数を定義し、変更できない値を作成できます。
- 📈 Rust は整数、浮動小数点数、ブール値、文字の4つの主要なスカラーデータ型をサポートしています。
- 🔢 Rust の整数型には、符号付きと符号なし、および異なるビットサイズ(8, 16, 32, 64, 128ビット)があります。
- 🔄 Rust は整数オーバーフローを検出し、デバッグビルドではパニックを起こし、リリースビルドでは2の補数巻戻しを行います。
- 📊 Rust はタプル型と配列型を備えており、タプルは異なる型の固定サイズのデータグループを表し、配列は固定長のデータ構造です。
- 🔧 Rust の関数は `fn` キーワードを使用して宣言され、引数を受け取ることができます。
- 🔄 Rust の制御フローには if 文、while ループ、for ループがあります。
- 📝 Rust には1行コメントとブロックコメントがあり、コードの説明や無効化に使用されます。
- 🔄 Rust 関数は値を返すことができます。最後の式は省略可能で、関数の戻り値として使用されます。
Q & A
Rust言語における変数の初期値設定はどのように行われますか?
-Rustでは、変数は`let`キーワードを使って初期値を設定します。例えば、`let x = 5;`のように宣言と同時に初期値を設定できます。
Rustにおける不変変数と可変変数の違いは何ですか?
-Rustでは、変数はデフォルトで不変(immutable)です。不変変数は一度値が設定されると、その後変更することができません。可変変数を作り、値を再代入するには、`let mut`を使用します。
Rustで定数を定義する方法は何ですか?
-Rustで定数を定義するには`const`キーワードを使用します。例えば、`const SUBSCRIBER_COUNT: u32 = 100_000;`のように、型注釈も必要です。定数は変更できないため、安全にグローバルにアクセスできます。
Rustにおけるシャドウイングとは何ですか?
-シャドウイングは、既存の変数名を使って新しい変数を宣言する機能です。これにより、前の変数が新しい変数によって遮られます。シャドウイングされた変数は、前の変数とは型が異なる場合もあります。
Rustのスカラーデータ型にはどのようなものがありますか?
-Rustのスカラーデータ型には、整数(整数型)、浮動小数点数(浮動小数点型)、ブール値(boolean型)、文字(character型)の4つがあります。
Rustのタプル型はどのように定義されるか?タプルの値を取得する方法は?
-タプル型は、異なる型のデータを含む固定サイズの配列のようなものです。定義は`(データ1, データ2, ...)`の形式で行われます。タプルの値を取得には、解構(destructuring)またはドット記法(dot notation)を使用できます。
Rustの配列はどのように宣言され、アクセスされるか?
-配列は`[データ1, データ2, ...]`の形式で宣言され、固定長です。配列の要素にアクセスするには、ブラケット記法(`配列名[index]`)を使用します。ただし、範囲外のインデックスにアクセスしようとすると、境界外例外が発生します。
Rustの関数はどのように定義されるか?
-関数は`fn`キーワードを使って定義されます。関数名はスネークケース(snake_case)で記述し、引数は括弧内に型注釈付きの名前を指定します。
Rustの制御フローにおいて、if文はどのように使われますか?
-Rustのif文は、条件が真である場合にコードブロックを実行します。else ifとelseブロックも使用でき、条件は明示的にブール値でなければなりません。
Rustのループにはどのような種類がありますか?
-Rustのループには、`loop`、`while`、および`for`の3種類があります。`loop`は無条件にループし、`while`は条件が真である間ループし、`for`はコレクションを反復処理するために使用されます。
Rustのコメントにはどのような種類がありますか?
-Rustには、単一行コメント(`//`)とブロックコメント(`/* ... */`)の2種類があります。また、文書コメント(`///`)もありますが、これは別の用途に使われます。
Rustの関数から値を返す方法は?
-Rustの関数は、`return`文を使って値を返すことができます。また、関数の最後の式は暗黙的に返されます。関数の戻り値の型は、関数定義の後ろに指定することができます。
Outlines
📚 欢迎来到Rust编程世界
本视频介绍了Rust编程语言的基础知识,包括变量、基本类型、函数、控制流和注释。首先,我们创建了一个名为'variables'的新Cargo项目,并讨论了Rust中变量的不可变性。通过创建一个名为'x'的变量并尝试重新赋值,我们展示了Rust中的错误处理。接着,我们学习了如何使变量可变,以及如何创建常量值。此外,还探讨了变量阴影的概念,以及如何通过类型注解来定义常量。最后,我们讨论了数据类型,包括标量数据类型(整数、浮点数、布尔值和字符)和复合数据类型(元组和数组),以及如何处理整数溢出。
🔢 Rust中的数据类型和函数
这一部分深入探讨了Rust中的标量数据类型,包括整数、浮点数、布尔值和字符。我们了解了Rust中整数的不同表示方式,以及如何处理整数溢出。浮点数部分介绍了默认的64位双精度浮点数。布尔值和字符类型也得到了简要介绍。接下来,我们讨论了复合数据类型,如元组和数组,以及如何从这些类型中获取值。此外,还介绍了函数的声明和调用,以及如何传递参数。最后,我们学习了表达式和语句的区别,以及如何在函数中返回值。
🔄 Rust的控制流和循环
这一段落介绍了Rust中的控制流,包括if语句和三种循环类型:无限循环(loop)、while循环和for循环。我们学习了如何在if语句中使用条件判断,以及如何在let语句中使用if-else表达式。循环部分,我们讨论了如何使用break语句来控制循环的执行。还介绍了如何从循环中返回值,以及如何使用for循环来遍历集合。最后,我们了解了Rust中的注释类型,包括单行注释和块注释。
Mindmap
Keywords
💡Rust
💡Variables
💡Immutability
💡Constants
💡Shadowing
💡Data Types
💡Control Flow
💡Functions
💡Comments
💡Tuples
💡Arrays
Highlights
Rust programming language tutorial
Chapter three covers basic programming concepts
Variables in Rust are immutable by default
To make a variable mutable, use the 'mut' keyword
Constants are declared with the 'const' keyword and must be type annotated
Constants cannot be mutated and must be set to constant expressions
Shadowing allows re-declaring a variable with the same name
Scalars represent single values, while compounds represent groups
Rust has four main scalar data types: integers, floating points, booleans, and characters
Integers in Rust can be signed or unsigned and have various sizes
Rust prevents integer overflow by performing two's complement wrapping
Floating point numbers are 64-bit double precision by default
Tuples are fixed-size arrays of different types
Arrays in Rust are fixed length and start at index zero
Functions in Rust are declared with the 'fn' keyword and follow snake case naming convention
Functions can take parameters and return values
Control flow in Rust includes if statements and loops
Loops in Rust include 'loop', 'while', and 'for' loops
Comments in Rust include single line, block, and documentation comments
Chapter three summary: variables, basic types, functions, comments, and control flow
Transcripts
welcome back to let's get rusty my name
is bogdan and this channel is
all about the rust programming language
if that sounds interesting to you
hover over that subscribe button and
give it a high five last time we went
over chapter two of the book and if you
haven't seen that video
make sure to check it out in this video
we're going over chapter three
in which we'll learn basic programming
concepts such as variables
basic types functions control flow and
comments with that
let's get started all right i went ahead
and created a new cargo project i assume
everyone knows how to do this but if you
don't go ahead and watch my previous
videos and you can name this project
whatever you'd like i chose to name
mines variables
now the first thing we're going to do is
start off by talking about variables
and immutability you might remember from
previous videos that variables are
immutable by default
in rust so to prove that out let's
create a new variable called
x and we'll set that equal to five
and then we'll print the variable
next we'll reassign it to something else
this case
six and we'll print it out again now i
didn't even have to compile this
to get an error because i have a
language server running so if i hover
over the red squigglies i could see that
we gave error saying you cannot assign
twice to an immutable variable
in this case x so let's say we did want
to make it immutable all we have to do
is
type in mu after the let keyword and now
we can reassign
x and we can go cargo run
and we see that x gets printed out as
five on the first line
and six on the second line or it also
has the concept
of constant values or values that can
never change
to create one we'll use the const
keyword and here i'll create one for my
subscriber count
i'll set the type to an unsigned 32-bit
integer
and make it equal 100 000.
we can all dream when declaring
constants it's common practice
to have the variable name be all
uppercase with
underscores where there are spaces now
you might ask why do we need constants
when variables in rest are
already immutable by default well there
are a few key differences between
constants and variables
the first is you cannot mutate a
constant so for example if i type in mu
in front of our constant i get an error
here that says
const globals cannot be mutable so if
you declare a constant you can be sure
that it will never be
mutated const variables must also be
type annotated
you can see here our constant is an
unsigned 32-bit integer
up here we didn't annotate our x
variable because rust referred that it
was a signed
32-bit integer but for constants we have
to annotate it constant
variables can also only be set to
constant expressions
for example with our variable x we could
have set it to the return value of a
function
but we cannot set constants to the
return value of a function
or any value that is computed at runtime
lastly here 100 000 might be hard to
read luckily rust allows us to make
numeric literals
more readable by adding an underscore
and there we have our constant with a
little warning telling us that
it's never used which is okay now the
last thing i want to talk about
on the subject of variables is shadowing
shadowing allows you to create a new
variable
using an existing name for example in
our program instead of making
x mutable we can remove the mute keyword
and then re-declare
x here now this first
x variable is shadowed by the second x
variable
this gives us two advantages first we
preserve mutability
this first x is still immutable and the
second x
is also immutable secondly we could
change types
so for example we could take the second
variable which is a six and instead of
an integer
we can make it a string now we can go
and run our program
and you can see that five is printed for
the first x and the string six
is printed for the second x next we'll
look at data types specifically scalar
data types and compound data types
scalar data types represent a single
value
while compound data types represent a
group of values
first let's talk about scalar data types
rust has
four main scalar data types which are
integers
floating point numbers booleans and
characters
integers are numbers without a
fractional component and here i have the
rust book pulled up
with a table showing you the integer
types in rust
every integer has a length and it could
either be signed
or unsigned signed integers could be
positive or negative numbers and
unsigned integers can only be
positive numbers integers could be 8
bits in size 16 bits 32 bits
64 bits 128 bits or arc which depends on
the architecture
usually either 64 or 32-bit rust
defaults integers to assign a 32-bit
integer
and as you can see we have different
ways of representing integers
decimal hex octal binary or byte
lastly let's talk about integer overflow
here i have an
8-bit unsigned integer which can hold a
max value
of 255. if i try to set this to a number
greater than 255 in debug builds
rust will panic and in release builds
rust will perform two's complement
wrapping
which means values greater than the
maximum will wrap around
back to the minimum values so 256 would
become zero
257 would become one also if you have a
language server running
and you try to change this to 256 you'll
get an
error warning you of the overflow rust
also supports floating point numbers
which are numbers with decimal points
and as you can see the default is a 64
bit double precision
floating point number and of course we
could do all our basic numeric
operations such as addition subtraction
multiplication
division and remainder next we have
booleans which represent the values true
or false and lastly we have the
character type which represents a
unicode character
is written with single quotes and
something we'll learn about more
in chapter eight next let's talk about
compound types which are types that
represent a group of values
first we have the tuple type which you
can think about as a fixed size array
of related data that could be of
different type here we have a tuple with
only two values
the first is a string representing a
youtube channel name
and the second is an integer
representing subscriber count
tuples are written by using a comma
separated list
inside of parentheses and you can see
here our type
is automatically annotated we can get
values out of tuples in two ways
the first is destructuring and the
second is dot notation
to destructure a tuple we'll create a
new set of variables
inside parentheses here we have channel
and sub count
and we'll set that equal to our tuple
setting this equal to our tuple we'll
take the first variable
and set that equal to the first value in
our tuple then it'll take the second
value
and set that equal to the second value
in our tuple we could also get values
out of tuples by using the dot notation
for example we'll create a new variable
called sub count and set that equal to
the tuple
value one two poles as well as arrays
both start at index zero to declare
arrays in rust
we use a comma separated list but
instead of parentheses we use
brackets in rust arrays are fixed length
if you want something that can change
size dynamically
you would have to use a vector which
we'll talk about more in chapter 8. to
access
individual values within an array we use
the standard bracket syntax here
erase could also be declared using this
syntax here which says create an array
with eight values
all set to zero lastly if we try to
access an index that's invalid for
example here we have a variable
x that accesses index three which does
not exist
we can type cargo run and we see that we
get a out of bounds
exception rust prevents us from doing
something that's memory unsafe and it's
able to do this because we know the size
of the array
next let's talk about functions and rest
functions can be declared using the fn
keyword
so here we'll define a function right
underneath main
and we'll simply make a print another
function rust uses the snake case
convention for function names meaning
that the function name should be all
lowercase
and whenever there's a space use an
underscore now we can call our new
function from main by specifying the
function name
and parentheses then we'll do cargo run
and we can see that our function was
called we can also allow our function to
take in parameters by specifying the
parameter name
and its type inside the parentheses we
can add multiple parameters by
separating them
with a comma like so and as you can see
we get an error here because our
function takes two arguments
but we're not passing any so let's pass
in some arguments
and let's also change our function to
print out the values passed in then we
can run our program
and we see our values printed out in
rest we could think about a piece of
code as either a statement
or an expression statements perform some
action but do not return a value
whereas expressions return a value as an
example inside of my function the print
line statements are
well statements because they don't
return anything here we created a new
variable called sum
which adds x and y together x plus y
here
is an expression because we add x and y
and return that value
in rest we can return values from a
function in two ways
the first way is to use the return
statement
here we're returning some and you can
see we get an error because the function
doesn't have
a return type to specify a return type
after the parentheses you can add a dash
and an arrow and then specify the return
type in this case a signed 32-bit
integer
inside of a function the last expression
is implicitly returned
so if we want to return sum we can
remove the return keyword
also for the last expression in the
function we omit the semicolon
we can simplify this further by removing
sum and just returning
x plus y then in our main function we
can create a new variable called
sum and set that equal to the return
value of our function
then we can print out our value let's
run our program and you can see
we print out 11 22 and the sum
all right now let's talk about control
flow first we have
if statements and if you've programmed
before the syntax should be very
familiar
you have an if block with a condition
and code that executes if that condition
is true we can have else if blocks
and finally we can have an else block if
all the other conditions
fail in rest however the condition must
be explicitly
a boolean so for example if we just try
to evaluate number
will get an error here we're trying to
evaluate an integer
but instead we need a bool lastly we can
use an if-else statement
inside of a let statement for example we
have this variable that's called
condition
we set it to true and then we have a
variable called number and we set that
to an if-else expression
if the condition is true the number is
five
else the number will be six next we'll
talk about the three different types of
loops in rust the most basic type of
loop we create using the loop
keyword what this will do is execute the
code inside of the loop until we call
break right now we don't call break at
all so if i run the program
it'll execute forever you can press ctrl
c
to exit the program we'll go back and
add a break statement
then we'll run our program again and
this time the loop only executes once
we can also return values from this type
of loop to show how this works let's
create a new mutable variable called
counter and set it equal
to zero then every time we run our loop
we'll increment counter
next we'll add a if statement to check
when counter gets to ten
and when it does we'll break out of the
loop and return counter
then we'll remove our previous break
statement adding counter after break
will make this loop
return counter now we can set the return
value to another variable in this case
we'll call it result
we'll need to add a semicolon to the end
of our loop
and print out the value now when we run
our program
we'll get 10 printed out there are two
other types of loops and rust the second
one is the classic while loop which will
execute as long as a certain condition
is true in this case we have a variable
called number set to three
and we're saying while the number does
not equal zero
execute the code inside the loop in this
case we'll just print the number
and decrement it then when we get to
zero we'll print the next line which is
left off if we run the program it will
print three two one
left off the last type of loop is a for
loop or a four
in loop and this is useful when you're
looping through a
collection so here we have a collection
of integers and we want to loop through
it to do that we'll type in 4
element in and then our variable name
which is a
dot which will give us an iterator for
the array
and then curly brackets finally we'll
print the element
this is saying for every element in our
array take that element and print it to
the screen we can also use the for loop
to loop over our range which is a type
provided by the standard library
which represents a sequence of numbers
as an example we could type in 4
number in and this time we'll do
parentheses
1 dot 4 curly brackets
and we'll print the number and
apparently the parentheses are not
required so we can remove those
okay so this is a range and what it will
do is create a sequence of numbers from
1
to 3 because the last number is
exclusive running the for loop on it
will do the same thing as before
we'll say for every number in this range
take the number
and print it out we can go ahead and run
our program and as you can see we get
the values in our
array and then we get the values in our
range and really quickly i just want to
go over comments
we have two basic types of comments in
rust there are single line comments
which you can write using two forward
slashes
and there are block comments which you
can write using a forward slash an
asterisk
and to end it an asterisk and a forward
slash there are also document comments
but we'll learn about that
at another time and there you have it
chapter 3 complete
we learned about variables basic types
functions
comments and control flow if you like
this video make sure to give it a like
and if you want more rust content make
sure to subscribe
and hit the notification bell to be
notified when new videos
come out i'll see you in the next one
5.0 / 5 (0 votes)