├── .github └── workflows │ └── mdlint.yml ├── .gitignore ├── .markdownlint.json ├── .typo-ci.yml ├── .vscode └── settings.json ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── SUMMARY.md ├── cn ├── CONTRIBUTING.md ├── README.md └── examples │ ├── README.md │ ├── section_1 │ ├── README.md │ ├── comment.md │ ├── hello_world.md │ ├── keywords.md │ ├── primitives.md │ ├── strings.md │ └── variables.md │ ├── section_2 │ ├── README.md │ ├── if-else.md │ ├── loops.md │ ├── match.md │ └── operator.md │ ├── section_3 │ ├── README.md │ ├── arrays.md │ ├── functions.md │ ├── methods.md │ └── struct.md │ └── section_4 │ ├── README.md │ ├── array-functions.md │ ├── files.md │ ├── json.md │ └── testing.md ├── code ├── hello_world │ └── hello.v ├── match-statement │ └── match_examples.v ├── methods │ └── methods.v └── variables │ ├── primitives.v │ └── variables.v ├── de ├── CONTRIBUTING.md ├── README.md └── examples │ ├── README.md │ ├── section_1 │ ├── README.md │ ├── comment.md │ ├── hello_world.md │ ├── keywords.md │ ├── primitives.md │ ├── strings.md │ └── variables.md │ ├── section_2 │ ├── README.md │ ├── if-else.md │ ├── loops.md │ ├── match.md │ └── operator.md │ ├── section_3 │ ├── README.md │ ├── arrays.md │ ├── functions.md │ ├── methods.md │ └── struct.md │ └── section_4 │ ├── README.md │ ├── array-functions.md │ ├── files.md │ ├── json.md │ └── testing.md ├── docs_style_guide.md ├── en └── examples │ ├── section_1 │ ├── README.md │ ├── comment.md │ ├── hello_world.md │ ├── keywords.md │ ├── primitives.md │ ├── strings.md │ └── variables.md │ ├── section_2 │ ├── README.md │ ├── if-else.md │ ├── loops.md │ ├── match.md │ └── operator.md │ ├── section_3 │ ├── README.md │ ├── arrays.md │ ├── functions.md │ ├── methods.md │ └── struct.md │ └── section_4 │ ├── README.md │ ├── array-functions.md │ ├── files.md │ ├── json.md │ └── testing.md ├── fr ├── section_1 │ ├── Beinvenue_monde.md │ ├── README.md │ ├── les_chaînes de caractères.md │ ├── les_commentaires.md │ ├── les_mots_clés.md │ ├── les_primitives.md │ └── les_variables.md ├── section_2 │ ├── README.md │ ├── if-else.md │ ├── loops.md │ ├── match.md │ └── operator.md ├── section_3 │ ├── README.md │ ├── arrays.md │ ├── functions.md │ ├── methods.md │ └── struct.md └── section_4 │ ├── README.md │ ├── array-functions.md │ ├── files.md │ ├── json.md │ └── testing.md ├── id ├── CONTRIBUTING.md ├── README.md └── examples │ ├── README.md │ └── section1 │ ├── README.md │ └── variables.md ├── it ├── CONTRIBUTING.md ├── README.md └── examples │ ├── README.md │ └── section_1 │ ├── README.md │ ├── comment.md │ ├── hello_world.md │ ├── keywords.md │ ├── primitives.md │ ├── strings.md │ └── variables.md ├── jp ├── CONTRIBUTING.md ├── README.md ├── code │ └── hello_world │ │ └── hello.v └── examples │ ├── section_1 │ ├── README.md │ ├── comment.md │ ├── hello_world.md │ ├── keywords.md │ ├── primitives.md │ ├── strings.md │ └── variables.md │ ├── section_2 │ ├── README.md │ ├── if-else.md │ ├── loops.md │ ├── match.md │ └── operator.md │ ├── section_3 │ ├── README.md │ ├── arrays.md │ ├── functions.md │ ├── methods.md │ └── struct.md │ └── section_4 │ ├── README.md │ ├── array-functions.md │ ├── files.md │ ├── json.md │ └── testing.md └── pt-br ├── CONTRIBUTING.md ├── README.md └── examples ├── README.md ├── section_1 ├── README.md ├── comment.md ├── keywords.md └── primitives.md └── section_2 ├── README.md └── operators.md /.github/workflows/mdlint.yml: -------------------------------------------------------------------------------- 1 | name: Markdown Lint 2 | on: [push, pull_request] 3 | jobs: 4 | ubuntu-latest: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - name: Installing MarkdownLint CLI 8 | run: sudo npm install -g markdownlint-cli 9 | - uses: actions/checkout@v1 10 | - name: Running MarkdownLint 11 | run: markdownlint **/*.md 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.exe 2 | *.o 3 | *.obj 4 | *.vrepl_temp.v 5 | *.tmp.c 6 | a.out.tmp.c 7 | *.vrepl.v 8 | *.vrepl* 9 | .vrepl_temp 10 | 11 | .DS_Store 12 | data/.DS_Store 13 | 14 | # examples executable files 15 | src/hello_world/hello_world 16 | src/hello_world/hello_world.exe 17 | main 18 | main.v 19 | -------------------------------------------------------------------------------- /.markdownlint.json: -------------------------------------------------------------------------------- 1 | { 2 | "MD013": false, 3 | "MD024": false, 4 | "MD033": false, 5 | "MD040": false, 6 | "MD029": false 7 | } 8 | -------------------------------------------------------------------------------- /.typo-ci.yml: -------------------------------------------------------------------------------- 1 | dictionaries: 2 | - de 3 | - en 4 | - en_GB 5 | - pt_BR 6 | 7 | # Files to exclude 8 | excluded_files: 9 | - "*.v" 10 | 11 | # Words to exclude 12 | excluded_words: 13 | - typoci 14 | - r'*' 15 | - r'Hello\nWorld' 16 | - variadic 17 | - palavras-chave 18 | - outras 19 | - linguagens 20 | - podem 21 | - ser 22 | - usados 23 | - uma 24 | - linguagem 25 | - muito 26 | - pequena 27 | - por 28 | - possui 29 | - poucas 30 | - Existem 31 | - cerca 32 | - Operadores 33 | - Esta 34 | - discute 35 | - principais 36 | - condicionais 37 | - suporta 38 | - seguintes 39 | - alterar 40 | - valores 41 | - inicializar 42 | - mundo 43 | - outras 44 | - linguagens 45 | - permite 46 | - menor 47 | - maior 48 | - igual 49 | - booleanos 50 | - mesmo 51 | - especiais 52 | - opcional 53 | - Operadores 54 | - Primitivos 55 | - tem 56 | - menos 57 | - tipos 58 | - pode 59 | - ser 60 | - inteiro 61 | - tipo 62 | - compostos 63 | - subclassificado 64 | - significa 65 | - positivo 66 | - negativo 67 | - apenas 68 | - Tamanho 69 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/v-community/v_by_example/339052b909f8ac683e69c8f9094e8b6a7634e688/.vscode/settings.json -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ## General 4 | 5 | Please ensure your pull request adheres to the following guidelines: 6 | 7 | * New example or improvements to existing examples are welcome. 8 | * Please check your spelling and grammar. 9 | 10 | ## A Note on Example Versions 11 | All examples should include the following header: 12 | 13 | ```markdown 14 | --- 15 | version: 3.5.1 16 | example_title: JSON 17 | --- 18 | ``` 19 | 20 | Change the `version` attribute according to the following rules: 21 | 22 | * MAJOR — You (re)wrote the whole thing. Your new content will need some translation. 23 | * MINOR — Added or removed some content, few sentences, etc. 24 | * PATCH — Spelling, typos. Probably not translated stuff. 25 | 26 | We follow [SemVer.org](https://semver.org) pattern. This is important because we use that to determine and inform translators of new content that requires translation. 27 | 28 | ## Adding a New Example 29 | 30 | To add a new example, create a new folder and a file or a file (depending upon the example) under the appropriate directory in `./examples`. Please check the `.plan` file to see what examples we plan to create. Feel free to work on any pending examples. We're happy to read/review your changes and collaborate/code with you to merge them. 31 | 32 | Thank you for your contributions! 33 | 34 | ## Getting started with the project 35 | 36 | ### 1. Fork and clone this repository 37 | 38 | [Fork this repository](https://github.com/v-community/v_by_example/fork) and clone your fork. If you don't know what forking means or don't know how to do it, nice instructions are available [here](https://help.github.com/articles/fork-a-repo/). 39 | 40 | #### 2. Make your changes and push them 41 | 42 | Now you're ready to make your changes! Once you're done with your changes, push those changes to your fork and then [submit a **pull request**](https://help.github.com/articles/using-pull-requests/). 43 | 44 | ## License 45 | 46 | This code is free to use under the terms of the MIT license. 47 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 The V Programming Language Community 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # V by Example 2 | 3 | **NOTE: This is very outdated and it will be updated and worked upon when V 1.0 is released.** 4 | 5 | [Brazilian Portuguese](pt-br/README.md) | [Deutsch](de/README.md) | [English](en/README.md) | [Bahasa Indonesia](id/README.md) | [Chinese](cn/README.md) | [Japanese](jp/README.md) | [Italian](it/README.md) | [French](fr/README.md) 6 | > Learn V by Examples 7 | 8 | V by Example is a direct introduction to V by using annotated program examples. 9 | 10 | - [Examples](#examples) 11 | - [Contributing](#contributing) 12 | - [License](#license) 13 | 14 | Discord: [https://discord.gg/vlang](https://discord.gg/vlang) 15 | 16 | ## Section 1 17 | 18 | Introduction to V by presenting a few basic examples and exercises. 19 | 20 | - [Hello World](en/examples/section_1/hello_world.md) 21 | - [V Keywords](en/examples/section_1/keywords.md) 22 | - [Primitives](en/examples/section_1/primitives.md) 23 | - [Variables](en/examples/section_1/variables.md) 24 | - [Strings](en/examples/section_1/strings.md) 25 | - [Comment](en/examples/section_1/comment.md) 26 | 27 | ## Section 2 28 | 29 | This section discusses the main operators and conditional statements in V. 30 | 31 | - [Operator](en/examples/section_2/operator.md) 32 | - [If-else](en/examples/section_2/if-else.md) 33 | - [Match](en/examples/section_2/match.md) 34 | - [Loops](en/examples/section_2/loops.md) 35 | 36 | ## Section 3 37 | 38 | A study on functions and methods and in the most important data structures in V: arrays and struct. 39 | 40 | - [Functions](en/examples/section_3/functions.md) 41 | - [Arrays](en/examples/section_3/arrays.md) 42 | - [Struct](en/examples/section_3/struct.md) 43 | - [Methods](en/examples/section_3/methods.md) 44 | 45 | ## Section 4 46 | 47 | In this section, we dive deeper and study the features inside the Array object. Other examples like JSON, Writing/reading files and Testing are covered. 48 | 49 | - [Array Functions](en/examples/section_4/array-functions.md) 50 | - [Testing](en/examples/section_4/testing.md) 51 | - [Files](en/examples/section_4/files.md) 52 | - [JSON](en/examples/section_4/json.md) 53 | 54 | ## Team 55 | 56 | Current list of maintainers/authors: 57 | 58 | - [Don Alfons Nisnoni](https://github.com/dhonx) 59 | - [Ivo-Balbaert](https://github.com/ibalbaert) 60 | - [Sven Patrick Meier](https://github.com/SuicideS3ason) 61 | - [Swastik Baranwal](https://github.com/Delta456) 62 | - [Vitor Oliveira](https://github.com/vbrazo) 63 | 64 | ## Contributing 65 | 66 | See our [CONTRIBUTING.md](CONTRIBUTING.md) and start contributing today. We usually elect new maintainers based on contributions. 67 | 68 | ## License 69 | 70 | [MIT](LICENSE) 71 | -------------------------------------------------------------------------------- /cn/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # 贡献 2 | 3 | ## 总则 4 | 5 | 请确保您的请求符合以下准则: 6 | 7 | * 欢迎新示例或对现有示例的改进。 8 | * 请检查你的拼写和语法。 9 | 10 | ## 添加新示例 11 | 12 | 要添加新示例,请在`./examples`中的相应目录下创建一个新文件夹和一个文件或一个文件(取决于示例)。请检查`.plan`文件,查看我们计划创建哪些示例。请随意处理任何悬而未决的例子。我们很高兴阅读/审阅您的更改,并与您协作/编写代码以合并它们。 13 | 14 | 谢谢你的贡献! 15 | 16 | ## 开始贡献项目 17 | 18 | ### 1. Fork和clone这个repository 19 | 20 | [Fork这个repository](https://github.com/v-community/v_by_example/fork) 和clone你的fork. 如果您不知道forking是什么意思或者不知道如何使用它,那么[这里](https://help.github.com/articles/fork-a-repo/) 提供了很好的说明。 21 | 22 | ### 2. 做出改变并提交它们 23 | 24 | 现在你准备好做出改变了!完成更改后,将这些更改推送到fork,然后[提交**请求**](https://help.github.com/articles/using-pull-requests/) 25 | 26 | ## 版权 27 | 28 | 根据MIT的许可条款,此代码是免费使用的。 29 | -------------------------------------------------------------------------------- /cn/README.md: -------------------------------------------------------------------------------- 1 | # V举例 2 | 3 | [Brazilian Portuguese](/pt-br/README.md) | [Deutsch](/de/README.md) | [English](/en/README.md) | [Bahasa Indonesia](/id/README.md) | [Chinese](README.md) 4 | 5 | > Learn V by Examples 6 | 7 | V by Example是使用带注释的程序示例对V语言的介绍。 8 | 9 | - [例子](#examples) 10 | - [贡献](#contributing) 11 | - [版权](#license) 12 | 13 | Discord: [https://discord.gg/d3Qk65J](https://discord.gg/d3Qk65J) 14 | 15 | ## Section 1 16 | 17 | 通过一些基本的例子和练习来介绍V语言。 18 | 19 | - [Hello World](examples/section_1/hello_world.md) 20 | - [V Keywords](examples/section_1/keywords.md) 21 | - [Primitives](examples/section_1/primitives.md) 22 | - [Variables](examples/section_1/variables.md) 23 | - [Strings](examples/section_1/strings.md) 24 | - [Comment](examples/section_1/comment.md) 25 | 26 | ## Section 2 27 | 28 | 本节讨论V语言中主要的运算和条件语句。 29 | 30 | - [Operator](examples/section_2/operator.md) 31 | - [If-else](examples/section_2/if-else.md) 32 | - [Match](examples/section_2/match.md) 33 | - [Loops](examples/section_2/loops.md) 34 | 35 | ## Section 3 36 | 37 | 学习V语言函数和方法以及最重要的数据结构:数组和结构体 38 | 39 | - [Functions](examples/section_3/functions.md) 40 | - [Arrays](examples/section_3/arrays.md) 41 | - [Struct](examples/section_3/struct.md) 42 | - [Methods](examples/section_3/methods.md) 43 | 44 | ## Section 4 45 | 46 | 在本节中,我们将深入研究数组对象内部的特征。其他的例子,比如JSON、写/读文件和测试,都会涉及到。 47 | 48 | - [Array Functions](examples/section_4/array-functions.md) 49 | - [Testing](examples/section_4/testing.md) 50 | - [Files](examples/section_4/files.md) 51 | - [JSON](examples/section_4/json.md) 52 | 53 | ## Team 54 | 55 | 当前维护者/作者列表: 56 | 57 | - [Don Alfons Nisnoni](https://github.com/dhonx) 58 | - [Ivo-Balbaert](https://github.com/ibalbaert) 59 | - [Sven Patrick Meier](https://github.com/SuicideS3ason) 60 | - [Swastik Baranwal](https://github.com/Delta456) 61 | - [Vitor Oliveira](https://github.com/vbrazo) 62 | 63 | ## Contributing 64 | 65 | 先阅读 [CONTRIBUTING.md](CONTRIBUTING.md) 然后开始贡献. 我们通常根据贡献来选择新的维护者。 66 | 67 | ## License 68 | 69 | [MIT](/LICENSE) 70 | -------------------------------------------------------------------------------- /cn/examples/README.md: -------------------------------------------------------------------------------- 1 | # 例子 2 | -------------------------------------------------------------------------------- /cn/examples/section_1/README.md: -------------------------------------------------------------------------------- 1 | # 第一节 2 | -------------------------------------------------------------------------------- /cn/examples/section_1/comment.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: 注释 4 | --- 5 | 6 | # 注释 7 | 8 | V支持单行注释`//`和多行注释`/**/`。 9 | 它们应该用于记录代码,以便让其他用户知道代码是如何工作的。 10 | 它还可以用于临时注释代码,以后必须使用。 11 | 12 | ```v 13 | // 这是单行注释 14 | 15 | /* 这是 16 | * 多行注释 17 | * /* 这也可以嵌套*/ 18 | */ 19 | ``` 20 | -------------------------------------------------------------------------------- /cn/examples/section_1/hello_world.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: 格式化打印 4 | --- 5 | 6 | # 格式化打印 7 | 8 | 打印由各种I/O流函数处理。人们应该要知道如何去使用它们。 9 | - `print`:用于将文本打印到不带换行符的输出流。 10 | - `println`:与`print`相同,但它会自动追加换行符。 11 | - `eprint`:与`print`相同,但它会输出到错误流(stderr)。 12 | - `eprintln`:与`println`相同,不过它会输出到错误流(stderr)。 13 | - `panic`:程序的输出和退出。 14 | 15 | ```v 16 | print('Hello World') 17 | print('Hello V') 18 | ``` 19 | 20 | 它在屏幕上将会打印 `Hello WorldHello V` 21 | 22 | 如果要在新行上打印下一行,则必须执行`\n`。 23 | 24 | ```v 25 | print('Hello World \n') 26 | print('Hello V ') 27 | ``` 28 | 29 | 如果不想使用`\n`,则可以使用`println`。 30 | 31 | # 注释 32 | 33 | V支持单行注释`//`和多行注释`/**/`。 34 | 它们应该用于记录代码,以便让其他用户知道代码是如何工作的。 35 | 它还可以用于临时注释代码,以后不得不使用。 36 | 37 | ```v 38 | // 这是单行注释 39 | 40 | /* 这是 41 | * 多行注释 42 | * /* 这也可以嵌套*/ 43 | */ 44 | ``` 45 | 46 | 47 | ## 练习 48 | 49 | 尝试在`hello.v`中删掉代码的注释,看看会发生什么。 50 | -------------------------------------------------------------------------------- /cn/examples/section_1/keywords.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: 关键字 4 | --- 5 | 6 | # 关键字 7 | 8 | V是一种非常小巧的语言,所以它很少有关键字。大约有25个关键字。 9 | 10 | | Keywords | in | V | Programming | Language | 11 | | -------- | ------ | --- | ----------- | --------- | 12 | | break | const | as | continue | defer | 13 | | else | enum | fn | for | struct | 14 | | go | goto | if | import | return | 15 | | type | pub | mut | in | interface | 16 | | match | module | or | none | | 17 | 18 | 与其他语言一样,它们不能用作变量。 19 | -------------------------------------------------------------------------------- /cn/examples/section_1/primitives.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Primitives 4 | --- 5 | 6 | # 基本类型 7 | 8 | V的基本类型比Go少。 9 | 10 | ## 基本数据类型 11 | 12 | - bool 也就是 `true` 或者 `false` 13 | 14 | - string 字符类型 15 | 16 | - 整数类型 `int` 17 | 18 | - 浮点数类型 `float` 19 | 20 | - rune (Unicode字符串) 21 | 22 | ## 复合类型 23 | 24 | - arrays `[]` 25 | 26 | - map `{}` 27 | 28 | - struct 29 | 30 | ## 整数 31 | 32 | 整数被细分为“signed”和“unsigned”。`signed`表示正或负,`unsigned`仅表示正。 33 | 34 | ### Signed Integer 35 | 36 | | 类型 | 大小 | 范围 | 37 | | ------ | :------: | --------------------------------------: | 38 | | int8 | 8 bits | -128 to 27 -1 | 39 | | int16 | 16 bits | -215 to 215 - 1 | 40 | | int | 32 bits | -231 to 231 - 1 | 41 | | int64 | 64 bits | -263 to 263 - 1 | 42 | | int128 | 128 bits | -2127 to 2127 - 1 | 43 | 44 | ### Unsigned Integer 45 | 46 | | 类型 | 大小 | 范围 | 47 | | ---- | :------: | -----------------------: | 48 | | byte | 8 bits | 0 to 27 -1 | 49 | | u16 | 16 bits | 0 to 215 - 1 | 50 | | u32 | 32 bits | 0 to 231 - 1 | 51 | | u64 | 64 bits | 0 to 263 - 1 | 52 | | u128 | 128 bits | 0 to 2127 - 1 | 53 | -------------------------------------------------------------------------------- /cn/examples/section_1/strings.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: 字符串 4 | --- 5 | 6 | # 字符串 7 | 8 | 在V中,可以使用`:=`运算符定义字符串。默认情况下,字符串(与其他变量一样)是不可变的。 9 | 一个可以使用`""`或 `''`来表示字符串。使用`vfmt`时,除非包含单引号字符,否则所有双引号字符串都将转换为单引号字符串。 10 | 11 | ```go 12 | name := 'Bob' 13 | println(name) // Bob 14 | println(name.len) // 3 15 | ``` 16 | 17 | 获取字符串的长度使用`.len`。 18 | 19 | ## 插入 20 | 21 | 可以在变量前面使用`$`进行字符串插值: 22 | 23 | ```go 24 | name:= 'Bob' 25 | println('Hello $name!') // Hello Bob! 26 | ``` 27 | 28 | 使用`${}`可以有更复杂的插值语法表达式: 29 | 30 | ```go 31 | struct User { 32 | name string 33 | age int 34 | } 35 | bob := User { 36 | name: 'Bob' 37 | age: 17 38 | } 39 | println('Say Hello to a new User: ${bob.name}, ${bob.age}') // Say Hello to new User: Bob, 17 40 | println('${bob.name}s age is higher or equal to 18: ${bob.age >= 18}') // 0 <=> number representation for false 41 | ``` 42 | 43 | ## 连接操作符 44 | 45 | 使用`+`运算符符字符串会被连接。 46 | 47 | ```go 48 | text := 'Hello' 49 | concatenated_text := text + ' World!' 50 | println(text) // Hello 51 | println(text + ' World!') // Hello World! 52 | println(concatenated_text) // Hello World! 53 | ``` 54 | 55 | 添加到字符串与连接可以使用`+=`运算符。因为字符串在默认情况下是不可变的,所以只有用`mut`声明它们时才能这样做。 56 | 57 | ```go 58 | mut hello := 'Hello ' 59 | hello += 'from V!' // 附加“从V!”到hello中存储的字符串。 60 | println(hello) // Hello from V! 61 | ``` 62 | 63 | 在V中,字符串数据使用UTF-8编码,字符串本身是一个只读字节数组。这使得切片成为可能,这意味着我们可以访问单个字符的文本或字符串变量的切片。 64 | ```go 65 | robert := 'Robert' 66 | bert := robert[2..robert.len] // bert 67 | rob := robert[0..3] // Rob 68 | println('The persons of interest are: $robert, $bert, $rob') // The persons of interest are: Robert, bert, Rob 69 | ``` 70 | 71 | ### Notes 72 | 73 | V中的所有运算符两边必须具有相同类型的值。下面的代码无法编译,因为`age`是`int`类型的: 74 | 75 | ```go 76 | age := 25 77 | println('age = ' + age) 78 | ``` 79 | 80 | 因此,我们需要使用`.str()`或使用字符串插值(最好用的方法)将其转换为字符串: 81 | 82 | ```go 83 | age := 25 84 | println('age = ' + age.str()) // age = 25 85 | println('age = $age') // age = 25 86 | ``` 87 | 88 | 要定义字符,可以使用:` `` `。原始字符串可以定义为前缀`r`。 89 | 90 | ```go 91 | hello := 'Hello\nWorld' 92 | println(hello) // Hello 93 | // World 94 | raw_hello := r'Hello\nWorld' 95 | println(raw_hello) // Hello\nWorld 96 | ``` 97 | -------------------------------------------------------------------------------- /cn/examples/section_1/variables.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: 变量 4 | --- 5 | 6 | # 变量 7 | 8 | 在V语言中,变量可以用`:=`运算符声明和初始化。变量只能以这种方式在V中声明,这意味着所有变量都有一个初始值。变量的类型是从右边的值推断出来的。默认情况下,V中的变量是不可变的。 9 | 10 | ```go 11 | age := 23 // int 12 | name := 'Alice' // string 13 | is_adult := age > 21 // bool 14 | 15 | println(age_str) // 23 16 | println(name) // Alice 17 | println(is_adult) // true 18 | ``` 19 | 20 | > Note:变量只能在函数中定义。所以在V中没有全局变量和全局状态。 21 | 22 | 要更改变量的值,要确保它必须是可变的。这可以在声明变量时使用`mut`关键字来完成。要给变量赋值,可以使用`=`。 23 | 24 | ```go 25 | mut age := 20 // 声明可变变量age并将其赋给值20。 26 | println(age) // 20 27 | age = 21 // 为age赋个新的值 28 | println(age) // 21 29 | ``` 30 | 31 | 在此处省略`mut`关键字将导致错误,因为无法更改不可变变量的值。 32 | 33 | ```go 34 | fn main() { 35 | age = 20 36 | println(age) 37 | } 38 | ``` 39 | 40 | 上面的代码在编译过程中会导致错误,因为未声明变量`age`, 41 | 42 | ```go 43 | fn main() { 44 | mut age := 20 // 我们声明可变变量age并将其赋给值20。 45 | println(age) // 20 46 | age := 21 // 错误 47 | } 48 | ``` 49 | 50 | 这里的`age:=21`在编译时将导致另一个错误,因为变量`age`已在作用域中定义。记住这一点很简单,只要用`:=`声明值并用`=`赋值。 51 | 52 | 像Go一样,您还可以使用`_`忽略掉不需要的值。通常用于多返回函数。 53 | 54 | ```go 55 | _ := "I don't need this value" 56 | println(_) // 错误:不能将“_”用作值 57 | ``` 58 | 59 | ## Naming Rules 60 | 61 | 以下是命名变量时应记住的规则。 62 | -名称不应该包含像`AlphaTest`这样的大写字母` 63 | -使用下划线作为分隔符,如`hello_world`` 64 | -名称应该尽可能具有描述性 65 | -名称不应该包含`__` 66 | -名称不应该包含任何空格 67 | -如果名称大于11,则必须要使用`_`作为分隔符 68 | 69 | 这些规则来自[`Snake_Case`](https://en.wikipedia.org/wiki/Snake_Case) V语言使用Snake Case,并且更喜欢它,因为它更易于阅读、书写和理解。 70 | 71 | ### 有效名称 72 | 73 | ```go 74 | boby 75 | john_dads 76 | myfamily_number 77 | ``` 78 | 79 | ### 无效名称 80 | 81 | ```go 82 | IamNotValid 83 | new Make 84 | ``` 85 | -------------------------------------------------------------------------------- /cn/examples/section_2/README.md: -------------------------------------------------------------------------------- 1 | # 第二节 2 | -------------------------------------------------------------------------------- /cn/examples/section_2/if-else.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: If语句 4 | --- 5 | 6 | # If语句 7 | 8 | ## `if` 表达式 9 | 10 | `if`语句是一个编程条件语句,如果被证明为真,则执行块中给定的代码。下面是V中if语句的一般示例: 11 | 12 | ```go 13 | john_height := 100 14 | maria_height := 178 15 | 16 | if john_height < maria_height { 17 | println("Maria is taller than John") 18 | } 19 | ``` 20 | 21 | 在上面的代码中,`println()`只在条件为true时执行。 22 | 条件周围不需要括号,并且始终需要大括号。 23 | 24 | ## `else` 语句 25 | 26 | `else`语句是一种编程条件语句,其中当`if`的计算结果为false时,`else`块中的代码将执行。 27 | 28 | ```go 29 | joey_age := 12 30 | kevin_age := 15 31 | if joey_age > kevin_age { 32 | println("Joey is older") 33 | } else { 34 | println("Kevin is older") 35 | } 36 | ``` 37 | 38 | 在本例中,`else`块中的代码将执行,因为`if`中的条件计算结果为`false`。 39 | 40 | ## `else if` 语句 41 | 42 | `if…else`语句根据测试表达式是`true`还是`false`执行两个不同的代码。有时,必须从两种以上的可能性中做出选择。`if……if……else`允许您在多个测试表达式之间进行检查并执行不同的语句。 43 | 44 | ```go 45 | tom_age := 20 46 | ashia_age := 38 47 | 48 | if tom_age < ashia_age { 49 | println("Tom is younger than Ashia") 50 | } else if tom_age > ashia_age { 51 | println("Tom is older than Ashia") 52 | } else { 53 | println("Tom and Ashia are the same age") 54 | } 55 | ``` 56 | 57 | 输出 58 | 59 | ```console 60 | Tom is younger than Asia 61 | ``` 62 | 63 | ## 嵌套的 `if..else` 语句 64 | 65 | 将`if…else`语句嵌套在另一个`if`或`else…if`语句中始终是一个好的做法,这意味着您可以在另一个`if`或`else…if`语句中使用一个`if`、`else`或`else…if`语句。 66 | 67 | ```go 68 | tom_age := 20 69 | ashia_age := 38 70 | 71 | if tom_age < ashia_age { 72 | if tom_age < 18 { 73 | println("tom_age < 18 and younger than Ashia.") 74 | } else { 75 | println("tom_age >= 18 and younger than Ashia.") 76 | } 77 | } else if tom_age > ashia_age { 78 | println("$tom_age > $ashia_age") 79 | } else { 80 | println("$tom_age == $ashia_age") 81 | } 82 | ``` 83 | 84 | 输出 85 | 86 | ```console 87 | tom_age >= 18 and younger than Ashia. 88 | ``` 89 | 90 | ## 使用 `if..else` 表达式 91 | 92 | `if..else`也可以用作表达式: 93 | 94 | ```go 95 | tom_age := 20 96 | ashia_age := 38 97 | 98 | s := if tom_age < ashia_age { 99 | "Tom is the youngest" 100 | } else { 101 | "Ashia is the youngest" 102 | } 103 | 104 | print(s) 105 | ``` 106 | 107 | 输出 108 | 109 | ```console 110 | Tom is the youngest 111 | ``` 112 | 113 | ## 练习 114 | 115 | 1.编写一个V程序来接受两个整数并检查它们是否相等。 116 | 2.编写一个V程序来检查给定的数字是偶数还是奇数。 117 | 3.编写一个V程序来检查给定的数字是正数还是负数。 118 | 4.写一个V程序来确定某一年是否是闰年。 119 | -------------------------------------------------------------------------------- /cn/examples/section_2/loops.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: 循环结构 4 | --- 5 | 6 | # 循环结构 7 | 8 | 在V语言中只有一种类型的循环,像Go一样,它可以在很多方面使用。 9 | 10 | ## `for`循环 11 | 12 | `for`循环提供了一种快速而简单的方法来重复做一些事情。 13 | 如果你想一次又一次地运行相同的代码,每次使用不同的值,它们都很方便。 14 | 你可以把一个循环想象成一个电脑版的游戏,告诉某人朝一个方向走X步,然后朝另一个方向走Y步; 15 | 例如,“向东走五步”可以用循环的方式来表达: 16 | 17 | ```go 18 | for i := 0; i < 5; i++ { 19 | println('Walking one step') 20 | } 21 | ``` 22 | 23 | V有`for`循环结构,循环可以用不同的方式编写: 24 | 25 | - 数组/映射的`in`运算符 26 | 27 | ```go 28 | ages := [18, 25, 32, 43, 50] 29 | 30 | for age in ages { 31 | println(age) 32 | } 33 | ``` 34 | 35 | > 注意:该值是只读的。 36 | 37 | - 带条件的`for`循环 38 | 39 | 这是一个控制流语句,允许基于给定的布尔条件重复执行代码。 40 | 条件周围没有括号,并且始终需要大括号。 41 | 42 | ```go 43 | mut factorial := 1 44 | mut counter := 1 45 | 46 | for { 47 | counter++ 48 | if counter > 5 { 49 | println(factorial) 50 | break 51 | } 52 | factorial = factorial * counter 53 | } 54 | 55 | println(counter) 56 | ``` 57 | 58 | 输出 59 | 60 | ```console 61 | 120 62 | 6 63 | ``` 64 | 65 | 带有break语句的for循环总是可以缩短代码,方法是将逆条件放在for之后,使其与其他语言中的while语句等价。 66 | 67 | ```go 68 | mut factorial := 1 69 | mut counter := 1 70 | 71 | for counter <= 5 { 72 | factorial = factorial * counter 73 | counter++ 74 | } 75 | println(factorial) 76 | println(counter) 77 | ``` 78 | 79 | 输出 80 | 81 | ```console 82 | 120 83 | 6 84 | ``` 85 | 86 | - 传统的C风格 87 | 88 | ```go 89 | mut factorial := 1 90 | mut counter := 1 91 | 92 | for counter = 1; counter < 6; counter++ { 93 | factorial = factorial * counter 94 | if counter == 5 { 95 | print(factorial) 96 | continue 97 | } 98 | println(counter) 99 | } 100 | ``` 101 | 102 | - 无限循环 103 | 104 | `for`循环也能无限循环 105 | 106 | ```go 107 | for { 108 | println('foo') 109 | } 110 | ``` 111 | 112 | ## 练习 113 | 114 | 1.写一个V程序来显示前10个自然数。 115 | 2.编写一个V程序,找出前10个自然数的和。 116 | 3.编写一个V程序来打印数组中的整数,并打印它们的平均值。 117 | 4.编写一个V程序,从键盘上读出10个数字,求出它们的和和和平均值。 118 | 5.编写一个V程序来显示一个整数之前的数的立方。 119 | -------------------------------------------------------------------------------- /cn/examples/section_2/match.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Match 4 | --- 5 | 6 | # Match 7 | 8 | ## match语句 9 | 10 | match语句是`if-else`的简写方法。 11 | 如果输入匹配,将执行第一个匹配分支的语句块,并返回其最后一个表达式。 12 | `else`分支将在没有其他匹配分支时执行。 13 | 14 | ```v 15 | num := 1 16 | match num % 2 == 0 { 17 | true { print('The input number is even.') } 18 | else { print('The input number is odd.') } 19 | } 20 | ``` 21 | 22 | 还可以使用`match`初始化变量,以便根据条件具有不同的值。 23 | 24 | ```v 25 | num := 3 26 | s := match num { 27 | 1 { 'one' } 28 | 2 { 'two' } 29 | else { 30 | 'many' 31 | } 32 | } 33 | ``` 34 | 35 | 例如: 36 | 37 | ```v 38 | fn even(num int) bool { 39 | match num % 2 == 0 { 40 | true { print('The input number is even.') } 41 | else { print('The input number is odd.') } 42 | } 43 | } 44 | 45 | fn num_to_str(num int) int { 46 | match num { 47 | 1 { 'one' } 48 | 2 { 'two' } 49 | else { 50 | 'many' 51 | } 52 | } 53 | } 54 | 55 | fn main() { 56 | println(even(14)) // 'The input number is even.' 57 | println(even(3)) // 'The input number is odd.' 58 | println(num_to_str(1)) // 'one' 59 | println(num_to_str(2)) // 'two' 60 | println(num_to_str(352)) // 'many' 61 | } 62 | ``` 63 | 64 | ### 枚举 65 | 66 | 还可以使用`variant`语句将`enum`值(变量)作为分支进行匹配: 67 | 68 | ```v 69 | enum Animal { 70 | cat 71 | dog 72 | goldfish 73 | pig 74 | } 75 | 76 | fn makes_miau(a Animal) bool { 77 | return match a { 78 | .cat { true } 79 | else { false } 80 | } 81 | } 82 | 83 | fn is_land_creature(a Animal) bool { 84 | return match a { 85 | .cat { true } 86 | .dog { true } 87 | .pig { true } 88 | else { 89 | false 90 | } 91 | } 92 | } 93 | // OR LIKE THAT 94 | fn is_land_creature_alt(a Animal) bool { 95 | return match a { 96 | .goldfish { false } 97 | else { 98 | true 99 | } 100 | } 101 | } 102 | 103 | fn main() { 104 | my_cat := Animal.cat 105 | my_goldfish := Animal.goldfish 106 | 107 | println(makes_miau(my_cat)) // true 108 | println(is_land_creature(my_cat)) // true 109 | println(is_land_creature(my_goldfish)) // false 110 | } 111 | ``` 112 | ### 练习 113 | 114 | 1.编写一个V程序,创建一个从1到50的所有偶数数组。 115 | 2.编写一个V程序,给定一个数字数组,返回最大值。 116 | 3.编写一个V程序来确定颜色(枚举)是红色还是蓝色 117 | -------------------------------------------------------------------------------- /cn/examples/section_2/operator.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: 运算符 4 | --- 5 | 6 | # 运算符 7 | 8 | V支持以下运算符: 9 | 10 | ## 基本运算符 11 | 12 | - `+` (加法) 用于 int, float和string 13 | 14 | - `-` (减法) 用于 int和float类型 15 | 16 | - `*` (乘法) 用于 int和float类型 17 | 18 | - `/` (除法) 用于 int和float类型 19 | 20 | - `%` (取模) 用于 int类型 21 | 22 | - `=` (赋值) 用于改变值 23 | 24 | - `:=` 用于初始化值 25 | 26 | ```v 27 | println(3 + 5) 28 | println(2.0 + 5.0) 29 | println('hello' + 'world') 30 | 31 | println(9 - 10) 32 | println(7.0 - 5.0) 33 | 34 | println(3 * 5) 35 | println(2.0 * 4) 36 | 37 | println(23 / 3) 38 | println(25.0 / 5.0) 39 | 40 | println(27 % 5) 41 | println(27 % 3) 42 | ``` 43 | 44 | 输出 45 | 46 | ```v 47 | 8 48 | 7.0 49 | hello world 50 | 51 | -1 52 | 2.0 53 | 54 | 15 55 | 8.0 56 | 57 | 7 58 | 5.0 59 | 60 | 2 61 | 0 62 | ``` 63 | 64 | > 注意:与其他语言不同,V不允许带浮点数的模。 65 | 66 | ## 比较运算符 67 | 68 | - `>`大于 69 | 70 | - `<`小于 71 | 72 | - `=`等于 73 | 74 | - `>=`大于或等于 75 | 76 | - `<=`小于或等于 77 | 78 | - `!=`不等于 79 | 80 | ## 布尔运算符 81 | 82 | - `&&`和 83 | 84 | - `||`或 85 | 86 | - `!`非 87 | 88 | ## 按位运算符 89 | 90 | - `<<`左位移 91 | 92 | - `>>`右位移 93 | 94 | - `&`按位和 95 | 96 | - `|`按位或 97 | 98 | - `^`按位异或 99 | 100 | ## 赋值运算符 101 | 102 | - `+=`与`foo=foo+var相同` 103 | 104 | - `-=`与`foo=foo-var相同` 105 | 106 | - `*=`与`foo=foo*var相同` 107 | 108 | - `/=`与`foo=foo/var相同` 109 | 110 | - `&=`与`foo=foo&var相同` 111 | 112 | - `|=`与`foo=foo'var相同` 113 | 114 | - `>=`与`foo=foo>>变量相同` 115 | 116 | - `<=`与`foo=foo< 注意:所有元素必须具有相同的类型。以下代码将无法编译。 41 | 42 | ```go 43 | mut users := ['vbrazo', 'donnisnoni95', 'Delta456', 0] 44 | ``` 45 | 46 | 输出 47 | 48 | ``` 49 | ~/main.v:2:43: bad array element type `int` instead of `string` 50 | ``` 51 | 52 | ## 创建空数组 53 | 54 | 如果要创建一个新的空数组,只需声明`[]`,后跟数据类型。 55 | 56 | ```go 57 | mut names := []string 58 | mut numbers := []int 59 | ``` 60 | 61 | ## 访问数组的元素 62 | 63 | ```go 64 | mut users := ['vbrazo', 'donnisnoni95', 'Delta456'] 65 | 66 | println(users[0]) 67 | println(users[2]) 68 | println(users[1]) 69 | ``` 70 | 71 | 输出 72 | 73 | ```go 74 | vbrazo 75 | Delta456 76 | donnisnoni95 77 | ``` 78 | 79 | ## 将值附加到数组 80 | 81 | `<<` 是将值附加到数组末尾的运算符。 82 | 83 | ```go 84 | mut ages := [18] 85 | ages << 47 86 | 87 | println(ages) 88 | ``` 89 | 90 | 数组 91 | 92 | ```go 93 | [18, 47] 94 | ``` 95 | 96 | 它还可以附加一个完整的数组。 97 | 98 | ```go 99 | mut ages := [18] 100 | ages << [47, 49] 101 | 102 | println(ages) 103 | ``` 104 | 105 | 输出 106 | 107 | ``` 108 | [18, 47, 49] 109 | ``` 110 | 111 | ## 数组的长度/大小 112 | 113 | `.len` 方法返回数组的长度。 114 | 115 | ```go 116 | mut names := ['Thiago', 'John'] 117 | 118 | println(names.len) 119 | ``` 120 | 121 | 输出 122 | 123 | ``` 124 | 2 125 | ``` 126 | 127 | ## In运算符 128 | 129 | `in` 检查元素是否在数组中。 130 | 131 | ```go 132 | mut names := ['Thiago', 'Alex', 'Joe'] 133 | 134 | println('Vitor' in names) 135 | println('Thiago' in names) 136 | ``` 137 | 138 | 输出 139 | 140 | ``` 141 | false 142 | true 143 | ``` 144 | 145 | ## 切片 146 | 147 | 在V中切片很容易,可以使用默认的 148 | V切片功能,无需调用`slice()`方法。 149 | 语法如下`my_array[start..end]` 150 | 151 | ```go 152 | animals := ['lion', 'goose', 'chicken', 'turkey', 'tiger'] 153 | poultry := animals[1..4] 154 | println(poultry) // ["goose", "chicken", "turkey"] 155 | ``` 156 | 157 | 如果要从索引的开头开始切片,只需将其忽略为放置`0`,然后改`“my_array[…end]`或`my_array[start…]`。 158 | 159 | ```go 160 | x := ['h', 'e', 'l', 'l', 'o'] 161 | y := x[..x.len-1] 162 | z := x[1..] 163 | println(y) // ['h', 'e', 'l', 'l'] 164 | println(z) // ['e', 'l', 'l', '0'] 165 | ``` 166 | 167 | ## 练习 168 | 1.编写一个V程序,将元素存储在数组中并打印出来。 169 | 2.编写一个V程序,读取数组中n个值,并按相反顺序显示。 170 | 3.编写一个V程序来查找数组中所有元素的和。 171 | 4.编写一个V程序,将一个数组的元素复制到另一个数组中。 172 | 5.编写一个V程序来计算数组中重复元素的总数。 173 | -------------------------------------------------------------------------------- /cn/examples/section_3/functions.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: 函数 4 | --- 5 | 6 | # Functions 7 | 8 | 函数是一个有组织、可重用的代码块,用于执行单个相关操作。 9 | 函数为应用程序提供了更好的模块性和高度的代码重用。 10 | 理想情况下,您应该考虑使用[单一责任原则](https://en.wikipedia.org/wiki/single_responsibility_principle) (SOLID),它声明每个模块或功能都应该有责任 11 | 对于软件提供的功能的单个部分,以保持代码的可维护性。 12 | 像C和Go一样,函数不能重载。 13 | 14 | ```go 15 | fn sum(x, y int) int { 16 | return x + y 17 | } 18 | 19 | println(sum(77, 33)) // 110 20 | ``` 21 | 22 | > 注意:类型在参数名之后。 23 | 24 | ```go 25 | fn full_name(first_name, last_name string) string { 26 | return first_name + ' ' + last_name 27 | } 28 | 29 | println(full_name("Vitor", "Oliveira")) // Vitor Oliveira 30 | ``` 31 | 32 | ## 函数变量 33 | 34 | 函数也可以是可变的,即接受无穷多个参数。 35 | 它们不是数组,不能返回。 36 | 37 | ```go 38 | fn foo(test ...string) { 39 | for txt in test { 40 | println(txt) 41 | } 42 | } 43 | 44 | foo("V", "is", "the", "best", "lang" , "ever") 45 | ``` 46 | 47 | 输出 48 | 49 | ```console 50 | V 51 | is 52 | the 53 | best 54 | lang 55 | ever 56 | ``` 57 | 58 | ## 多返回函数 59 | 60 | 与Go类似,V中的函数也可以返回多个不同类型的函数。 61 | 62 | ```go 63 | fn student(name string, age int) (string, int) { 64 | return name, age 65 | } 66 | 67 | name, age := student("Tom", 15) 68 | println(name1) 69 | println(age1) 70 | ``` 71 | 72 | 输出 73 | 74 | ```console 75 | Tom, 15 76 | ``` 77 | 78 | ## 高阶函数 79 | 80 | V中的函数也可以接受另一个函数作为参数 81 | 需要排序、映射、筛选等。 82 | 83 | ```go 84 | fn square(num int) int { 85 | return num * num 86 | } 87 | 88 | fn run(value int, op fn(int) int) int { 89 | return op(value) 90 | } 91 | 92 | println(run(10, square)) // 100 93 | ``` 94 | 95 | ## 命名规则 96 | 97 | 以下是命名函数时应记住的规则。 98 | 99 | - 名称不应包含像`AlphaTest`这样的大写字母` 100 | 101 | - 使用下划线作为分隔符,如`hello_world` 102 | 103 | - 名称不应以开头`_` 104 | 105 | - 名称应尽可能具有描述性 106 | 107 | - 名称不应包含`__` 108 | 109 | - 名称不应包含任何空格 110 | 111 | 这些规则来自[`Snake_Case`](https://en.wikipedia.org/wiki/Snake_Case) V使用Snake Case,并且更喜欢它,因为它更易于阅读、书写和理解。 112 | 113 | ### 有效名称 114 | 115 | ```go 116 | fn i_am_valid() 117 | fn thisworkstoo() 118 | fn print_values_through_struct() 119 | ``` 120 | 121 | ### 无效名称 122 | 123 | ```go 124 | fn IamNotValid() 125 | fn _print() 126 | fn print__logs() 127 | fn new Make Lexer() 128 | ``` 129 | 130 | ## Exercises 131 | 132 | 1. Write a V program to find the square of any number using the function. 133 | 2. Write a V program to check a given number is even or odd using the function. 134 | 3. Write a V program to convert decimal number to binary number using the function. 135 | 4. Write a V program to check whether a number is a prime number or not using the function. 136 | 5. Write a V program to get the largest element of an array using the function. 137 | -------------------------------------------------------------------------------- /cn/examples/section_3/methods.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Methods 4 | --- 5 | 6 | # Methods 7 | 8 | V没有Class。但是可以为类型定义方法。 9 | 方法是一个具有特殊接收器参数的函数, 10 | 只有指定类型的接收器才能执行此函数。 11 | 接收方在`fn`和方法名之间有自己的参数列表。 12 | 13 | ```go 14 | struct User { 15 | name string 16 | email string 17 | mut: 18 | age int 19 | } 20 | 21 | fn (u User) can_register() bool { 22 | return u.age > 15 23 | } 24 | 25 | fn (u mut User) has_birthday() { 26 | u.age += 1 27 | } 28 | 29 | fn main() { 30 | mut bob := User { 31 | name: 'Bob' 32 | email: 'bob@bob.com' 33 | age: 15 34 | } 35 | alice := User { 36 | name: 'Alice' 37 | email: 'alice@alice-mail.com' 38 | age: 17 39 | } 40 | println(bob.can_register()) 41 | println("Bob needs to be 16 to register, but he only is ${bob.age}.") 42 | println(alice.can_register()) 43 | bob.has_birthday() 44 | println(bob.age) 45 | } 46 | ``` 47 | 48 | 输出 49 | 50 | ```console 51 | false 52 | Bob needs to be 16 to register, but he only is 15. 53 | true 54 | 16 55 | ``` 56 | 57 | 上面的代码实现了两种类型为`User`的接收器`u`的方法。 58 | 注意,`has\birthday()`方法有一个mut接收器,这是必需的,因为我们要更改它的数据。 59 | V的惯例不是使用诸如`self、this`之类的接收者名字,而是一个短的,最好是一个只有一个字母的名字。 60 | 61 | ## 练习 62 | 1.为`Person`类型创建一个确定某人是否未成年的方法。 63 | 2.创建一个确定`Animal`是否有毛发的方法。 64 | -------------------------------------------------------------------------------- /cn/examples/section_3/struct.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Struct 4 | --- 5 | 6 | # Struct 7 | 8 | struct是一种复合数据类型(或记录)声明,它在内存块中的一个名称下定义物理分组的变量列表,允许通过单个指针或通过返回相同地址的struct声明的名称访问不同的变量。 9 | 对于来自[OOP]https://en.wikipedia.org/wiki/Object-oriented_programming) 语言的人来说,它可以被认为是“类”,但有更多的限制。 10 | 11 | ```go 12 | struct User { 13 | name string 14 | email string 15 | country string 16 | } 17 | 18 | fn main() { 19 | user := User { 20 | name: "V developers" 21 | email: "developers@vlang.io" 22 | country: "Canada" 23 | } 24 | 25 | println(user.country) 26 | } 27 | ``` 28 | 29 | > 注意:结构是在堆栈上分配的。 30 | 31 | 创建结构的新实例时,可以使用逗号分隔每个字段。当您想在一行上创建一个新实例时,它很有用。 32 | 33 | ```go 34 | user := User { name: "V developers", email: "developers@vlang.io", country: "Canada" } 35 | ``` 36 | 37 | ## 前缀`&` 38 | 39 | 您还可以在堆上分配一个结构,并使用`&`前缀获取对它的引用,如下所示: 40 | 41 | ```go 42 | user := &User{"V developers", "developers@vlang.io", "Canada"} 43 | println(user.name) 44 | ``` 45 | 46 | `user`的类型是`&user`。它是对`User`的引用。 47 | 48 | ## 访问修饰符 49 | 50 | 默认情况下,结构字段是`private`和`immutable`。它们的访问修饰符可以用`pub`和`mut`更改。 51 | 52 | ```go 53 | struct User { 54 | email string // private and immutable (default) 55 | } 56 | ``` 57 | 58 | 您可以将它们定义为`private mutable`。 59 | 60 | ```go 61 | struct User { 62 | email string 63 | mut: 64 | first_name string // private mutable 65 | last_name string // (you can list multiple fields with the same access modifier) 66 | } 67 | ``` 68 | 69 | 您还可以将它们定义为`public immutable`(只读)。 70 | 71 | ```go 72 | struct User { 73 | email string 74 | mut: 75 | first_name string 76 | last_name string 77 | pub: 78 | sin_number int // public immutable (readonly) 79 | } 80 | ``` 81 | 82 | 或作为`public`,但仅在父模块中是`mutable`。 83 | 84 | ```go 85 | struct User { 86 | email string 87 | mut: 88 | first_name string 89 | last_name string 90 | pub: 91 | sin_number int 92 | pub mut: 93 | phone int // public, but mutable only in parent module 94 | } 95 | ``` 96 | 97 | 或父模块内外的`public`和`mutable`。 98 | 99 | ```go 100 | struct User { 101 | email string 102 | mut: 103 | first_name string 104 | last_name string 105 | pub: 106 | sin_number int 107 | pub mut: 108 | phone int 109 | __global: 110 | address_1 string // public and mutable both inside and outside parent module 111 | address_2 string // (not recommended to use, that's why the 'global' keyword 112 | city string // starts with __) 113 | country string 114 | zip string 115 | } 116 | ``` 117 | 118 | ## 命名规则 119 | 120 | - `struct`的名称应始终为大写。 121 | 122 | - 变量命名使用[`Snake_Case`](https://github.com/v-community/v_by_example/blob/master/en/examples/section_1/variables.md#naming-rules) 。 123 | 124 | ## 练习 125 | 1.创建存储和显示“用户”信息的结构。 126 | 2.创建一个包含“x”和“y”字段的“Point”结构,并用private和public保护它们。 127 | -------------------------------------------------------------------------------- /cn/examples/section_4/README.md: -------------------------------------------------------------------------------- 1 | # 第四节 -------------------------------------------------------------------------------- /cn/examples/section_4/array-functions.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: 数组函数 4 | --- 5 | 6 | # 数组函数 7 | 8 | ## `repeat` 9 | 10 | 语法 11 | 12 | ```go 13 | array.repeat(number type) 14 | ``` 15 | 16 | 生成具有给定元素次数的数组。 17 | 18 | ```go 19 | foo := [1, 2].repeat(5) 20 | println(foo) // [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] 21 | ``` 22 | 23 | ## `delete` 24 | 25 | 语法 26 | 27 | ```go 28 | array.delete(ix type) 29 | ``` 30 | 31 | 删除索引`ix`处数组中的元素。 32 | 33 | ```go 34 | mut even_numbers := [2, 4, 6, 8, 10] 35 | even_numbers.delete(3) 36 | println(even_numbers) // [2, 4, 6, 10] 37 | ``` 38 | 39 | ## `reverse` 40 | 41 | 语法 42 | 43 | ```go 44 | array.reverse() 45 | ``` 46 | 47 | 反转数组。 48 | 49 | ```go 50 | float_num := [1.1, 1.3, 1.25, 1.4] 51 | float_num.reverse() // [1.4, 1.25, 1.3, 1.1] 52 | ``` 53 | 54 | ## `clone` 55 | 56 | 语法 57 | 58 | ```go 59 | array.clone() 60 | ``` 61 | 62 | 克隆并返回一个新数组。 63 | 64 | ```go 65 | foo := [1, 2, 4, 5, 4, 6] 66 | foo1 := foo.clone() 67 | println(foo1) // [1, 2, 4, 5, 4, 6] 68 | ``` 69 | -------------------------------------------------------------------------------- /cn/examples/section_4/files.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: 文件操作 4 | --- 5 | 6 | # 文件操作 7 | 8 | V中的文件是程序可访问的任何文件对象的抽象,与`os`库密切相关。 9 | 10 | ## 读取文件 11 | 12 | 读取文件是解决计算机科学中几个不同问题的重要任务。为了完成此任务,您可以使用V native library`os`,如下所述: 13 | 14 | ```go 15 | import os 16 | 17 | fn main() { 18 | mut fp := flag.new_flag_parser(os.args) 19 | generator := fp.string('generator', '', 'generator name') 20 | method := fp.string('method', '', 'generator method name') 21 | path := './data/$generator/$method' 22 | 23 | if os.file_exists(path) { 24 | print_generator_sample(path) 25 | } else { 26 | println('File does not exist') 27 | return 28 | } 29 | } 30 | 31 | fn print_generator_sample(path string) { 32 | contents := os.read_file(path.trim_space()) or { 33 | println('Failed to open $path') 34 | return 35 | } 36 | 37 | lines := contents.split_into_lines() 38 | length := lines.len 39 | 40 | print_random_element(lines, length) 41 | } 42 | 43 | fn print_random_element(lines []string, length int) { 44 | rand.seed(time.now().uni) 45 | 46 | println(lines[rand.next(length-1)]) 47 | } 48 | ``` 49 | 50 | ## 写入文件 51 | 52 | 在V中写入文件类似于读取文件。 53 | 54 | ```go 55 | import os 56 | 57 | fn main() { 58 | path := './data/file.txt' 59 | text := 'Full text description.' 60 | 61 | if contents := os.write_file(path, text) or { 62 | println('Failed while creating file') 63 | return 64 | } 65 | 66 | content_lines = read_file(path) 67 | print(content_lines) 68 | } 69 | 70 | fn read_file(path string) { 71 | contents := os.read_file(path.trim_space()) or { 72 | println('Failed to open $path') 73 | return 74 | } 75 | 76 | return contents.split_into_lines() 77 | } 78 | ``` 79 | 80 | ## 练习 81 | 1.编写一个V程序来创建一个包含内容的新文件。 82 | 2.编写一个V程序来读取两个不同的文件并显示其内容。 83 | 3.阅读V中“os”库的工作原理,了解如何使用它。 84 | 4.编码一个嵌套的json字符串并用结果编写一个新文件。 85 | -------------------------------------------------------------------------------- /cn/examples/section_4/json.md: -------------------------------------------------------------------------------- 1 | # JSON 2 | 3 | JavaScript对象表示法(JSON)是一种轻量级的数据交换格式,便于人们读写。此外,机器生成和/或解析也同样简单。 4 | JSON完全不依赖于语言,因此它是理想的交换格式。 5 | 6 | 要了解更多关于JSON的信息,请访问: [json.org](http://json.org). 7 | 8 | ## 解析JSON 9 | 10 | 解析由另一个应用程序接收的JSON字符串,或在现有应用程序中生成的JSON字符串: 11 | 12 | ```go 13 | import json 14 | 15 | struct Customer { 16 | first_name string 17 | last_name string 18 | hometown string 19 | } 20 | 21 | fn main() { 22 | customers_string := '[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro" }, { "first_name": "Don", "last_name": "Nisnoni", "hometown": "Kupang" }]' 23 | customers := json.decode([]Customer, customers_string) or { 24 | eprintln('Failed to parse json') 25 | return 26 | } 27 | 28 | // Print the list of customers 29 | for customer in customers { 30 | println('$customer.first_name $customer.last_name: $customer.hometown') 31 | } 32 | } 33 | ``` 34 | 35 | ## 生成JSON 36 | 37 | 创建用于通信或序列化的JSON字符串也很简单。我们在下面的示例中解码和编码: 38 | 39 | ```go 40 | import json 41 | 42 | struct Customer { 43 | first_name string 44 | last_name string 45 | hometown string 46 | } 47 | 48 | fn main() { 49 | customer_string := '[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro"}]' 50 | 51 | customer := json.decode([]Customer, customer_string) or { 52 | eprintln('Failed to parse json') 53 | return 54 | } 55 | 56 | encoded_json := json.encode(customer) 57 | 58 | println(encoded_json) 59 | } 60 | ``` 61 | 62 | ## 练习 63 | 1.比较您在最喜欢的语言和V中处理JSON的方式。 64 | 2.构建包含地址信息的“Address”结构。 65 | 3.使用“Address”结构对包含JSON格式的字符串进行解码和编码。 66 | 4.创建两个结构:`Address`和`User`,其中一个用户有许多地址。现在接收一个带有嵌套JSON的字符串,比如`'[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro", "addresses": [{ street_name: "Rua Princesa Isabel", city: "Rio de Janeiro", country: "Brazil" }] }]'`,对其进行解码和编码。 -------------------------------------------------------------------------------- /cn/examples/section_4/testing.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: 测试 4 | --- 5 | 6 | # 测试 7 | 8 | 软件开发中的测试是一个过程,其目的是评估应用程序的功能,以确定代码是否满足指定的要求,并确定问题,以确保产品具有预期的质量。 9 | 10 | ## 自动化测试 11 | 12 | 自动化测试遵循使用自动化工具测试软件以发现缺陷的过程。在这个过程中,程序员使用自动化工具执行测试脚本并自动生成测试结果。 13 | 14 | ## V中的测试 15 | 16 | 在V中,所有的测试文件都必须使用以下格式命名:`*u test.V`并且函数应该以`test`开头。 17 | 18 | ```go 19 | // sum.v in subfolder sum 20 | module sum 21 | 22 | pub fn sum(a, b int) int { 23 | return a + b 24 | } 25 | ``` 26 | 27 | ```go 28 | // sum_test.v 29 | import sum 30 | 31 | fn test_sum() { 32 | assert sum.sum(2, 3) == 5 33 | // assert sum.sum(2, 3) == 777 // => sum_test.v:6: FAILED assertion 34 | } 35 | ``` 36 | 37 | 要执行测试,应执行`v test_sum.v`。 38 | 39 | ### 练习 40 | 41 | 1. 测试JSON结构: 42 | 43 | ```go 44 | import json 45 | 46 | fn test_encode_customer(){ 47 | customer := Customer{ first_name: "Vitor", last_name: "Oliveira" } 48 | expected := '{ "first_name": "Vitor", "last_name": "Oliveira" }' 49 | 50 | encoded_json := json.encode(customer) 51 | assert encoded_json == expected 52 | } 53 | ``` 54 | 55 | 2. 测试文件: 56 | 57 | ```go 58 | import os 59 | 60 | fn test_file_creation() { 61 | file_name := './new_file.txt' 62 | content := 'text' 63 | 64 | os.write_file(file_name, content) 65 | assert content.len == os.file_size(file_name) 66 | 67 | os.rm(file_name) 68 | } 69 | ``` 70 | -------------------------------------------------------------------------------- /code/hello_world/hello.v: -------------------------------------------------------------------------------- 1 | // Single line comments 2 | 3 | /* This is a multiline comment. 4 | * /* It can also be nested. */ 5 | * 6 | */ 7 | 8 | print('Hello V\n') 9 | print('Hello World') 10 | 11 | // This will print on a new line automatically 12 | // println('Hello V by Example') 13 | // eprintln('Hello V by Example') 14 | 15 | /*println('I am Bob and I am $age old') */ // This won't print because `age` isn't defined. 16 | /* println(foo) */ // Also wouldn't work because custom str func not defined . 17 | 18 | //panic('Exiting from the program') 19 | -------------------------------------------------------------------------------- /code/match-statement/match_examples.v: -------------------------------------------------------------------------------- 1 | fn main() { 2 | numbers := create_even_numbers_to_fifty() 3 | println('Creating an array just containing even numbers from 0 to 50:\n$numbers\n') 4 | println('The maximum of the given array is: ' + max_val(numbers).str()) 5 | 6 | red_col := Color.red 7 | green_col := Color.green 8 | grey_col := Color.grey 9 | println('The color $green_col is red or blue: ' + is_red_or_blue(green_col).str()) 10 | println('The color $red_col is red or blue: ' + is_red_or_blue(red_col).str()) 11 | println('The color $grey_col is red or blue: ' + is_red_or_blue(grey_col).str()) 12 | 13 | println(num_str(2)) // 'two' 14 | println(num_str(5)) // 'many' 15 | } 16 | 17 | fn num_str(num int) string { 18 | return match num { 19 | 1 { 'one' } 20 | 2 { 'two' } 21 | else { 22 | 'many' 23 | } 24 | } 25 | } 26 | 27 | fn create_even_numbers_to_fifty() []int { 28 | mut numbers := []int{} 29 | for i := 0; i <= 50; i++ { 30 | match i % 2 { 31 | 0 { numbers << i } 32 | else { 33 | continue 34 | } 35 | } 36 | } 37 | return numbers 38 | } 39 | 40 | fn max_val(numbers []int) int { 41 | mut maximum := 0 42 | for num in numbers { 43 | match num > maximum { 44 | true { 45 | //println('current number: ' + num.str()) 46 | maximum = num 47 | } 48 | else { continue } 49 | } 50 | } 51 | return maximum 52 | } 53 | 54 | enum Color { 55 | red 56 | blue 57 | green 58 | violet 59 | pink 60 | black 61 | white 62 | gray 63 | grey 64 | purple 65 | yellow 66 | } 67 | 68 | fn is_red_or_blue(c Color) bool { 69 | return match c { 70 | .red { true } 71 | .blue { true } 72 | else { false } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /code/methods/methods.v: -------------------------------------------------------------------------------- 1 | struct User { 2 | name string 3 | email string 4 | mut: 5 | age int 6 | } 7 | 8 | fn (u User) can_register() bool { 9 | return u.age > 15 10 | } 11 | 12 | fn (mut u User) has_birthday() { // mut needed to change fields 13 | u.age++ 14 | } 15 | 16 | // Below function gives error as field email is immutable 17 | // fn (mut u User) change_email() { 18 | // u.email = 'abcd@efgh.com' 19 | // } 20 | 21 | fn main() { 22 | mut bob := User { 23 | name: 'Bob' 24 | email: 'bob@bob.com' 25 | age: 15 26 | } 27 | alice := User { 28 | name: 'Alice' 29 | email: 'alice@alice-mail.com' 30 | age: 17 31 | } 32 | println(bob.can_register()) // false 33 | println('Bob needs to be 16 to register, but he only is ${bob.age}.') // Bob needs to be 16 to register, but he only is 15. 34 | println(alice.can_register()) // true 35 | bob.has_birthday() 36 | println(bob.age) // 16 37 | // alice.has_birthday() // Gives error as alice is immutable 38 | } 39 | -------------------------------------------------------------------------------- /code/variables/primitives.v: -------------------------------------------------------------------------------- 1 | fn main() { 2 | a:=byte(10) 3 | b:=u16(10000) 4 | c:=u32(1000000) 5 | d:=u64(10000000000) 6 | // e:=u128(10000000000000000000000) // soon 7 | 8 | println(typeof(a)) // byte 9 | println(typeof(b)) // u16 10 | println(typeof(c)) // u32 11 | println(typeof(d)) // u64 12 | 13 | f := i8(-1) 14 | g := i16(-1000) 15 | h := int(-100000) 16 | i := i64(-1000000000) 17 | // j := i128(-10000000000000000000000000000) // soon 18 | println(typeof(f)) // i8 19 | println(typeof(g)) // i16 20 | println(typeof(h)) // int 21 | println(typeof(i)) // i64 22 | mut k := 100 23 | mut m := byte(10032) 24 | 25 | println(typeof(k)) // int 26 | println(typeof(m)) // byte 27 | println(int(m)) // 48 28 | println(m) // 0 (character represented by byte(48)) 29 | 30 | k = 1000000000000000000 // overflow 31 | 32 | println(typeof(k)) // int 33 | println(k) // -1486618624 34 | 35 | n := f32(2) 36 | p := f64(2) 37 | mut q := 2.0 38 | 39 | println(typeof(n)) // f32 40 | println(typeof(p)) // f64 41 | println(typeof(q)) // f64 42 | println(q) // 2. 43 | 44 | q = 1 45 | 46 | println(q) // 1. 47 | 48 | q = 1.2 49 | 50 | println(q) // 1.2 51 | } -------------------------------------------------------------------------------- /code/variables/variables.v: -------------------------------------------------------------------------------- 1 | fn main() { 2 | age := 23 // int 3 | name := 'Alice' // string 4 | is_male := false // bool 5 | is_adult := age > 21 // bool 6 | mut email := 'alice@alice-mail.com' //string 7 | mut num_phone := 2 //int 8 | 9 | // addr = 'abcd' // error as assignment must be done with := 10 | // fn := 1 // error as keyword cannot be identifier (see keywords.md) 11 | 12 | println(age) // 23 13 | println(name) // Alice 14 | println(is_male) // false 15 | println(is_adult) // true 16 | println(email) // alice@alice-mail.com 17 | println(num_phone) // 2 18 | 19 | email = 'alice@other.com' // assigning new value 20 | num_phone += 2 // shorthand assignment 21 | 22 | println(email) // alice@other.com 23 | println(num_phone) // 4 24 | 25 | // age = 24 // error as it is immutable 26 | // email = 2 // error as RHS (2) is of different type than LHS (email) 27 | 28 | } 29 | -------------------------------------------------------------------------------- /de/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ## General 4 | 5 | Please ensure your pull request adheres to the following guidelines: 6 | 7 | * New example or improvements to existing examples are welcome. 8 | * Please check your spelling and grammar. 9 | 10 | ## Adding a New Example 11 | 12 | To add a new example, create a new folder and a file or a file (depending upon the example) under the appropriate directory in `./examples`. Please check the `.plan` file to see what examples we plan to create. Feel free to work on any pending examples. We're happy to read/review your changes and collaborate/code with you to merge them. 13 | 14 | Thank you for your contributions! 15 | 16 | ## Getting started with the project 17 | 18 | ### 1. Fork and clone this repository 19 | 20 | [Fork this repository](https://github.com/v-community/v_by_example/fork) and clone your fork. If you don't know what forking means or don't know how to do it, nice instructions are available [here](https://help.github.com/articles/fork-a-repo/). 21 | 22 | #### 2. Make your changes and push them 23 | 24 | Now you're ready to make your changes! Once you're done with your changes, push those changes to your fork and then [submit a **pull request**](https://help.github.com/articles/using-pull-requests/). 25 | 26 | ## License 27 | 28 | This code is free to use under the terms of the MIT license. 29 | -------------------------------------------------------------------------------- /de/README.md: -------------------------------------------------------------------------------- 1 | # V mit einem Beispiel 2 | 3 | [Brazilian Portuguese](/pt-br/README.md) | [Deutsch](README.md) | [English](/en/README.md) | [Bahasa Indonesia](/id/README.md) | [Chinese](/cn/README.md) 4 | 5 | > Learn V by Examples 6 | 7 | V by Example ist eine Einführung in V anhand von begleitenden, erklärten Codebeispielen. 8 | 9 | * [Beispiele](examples/README.md) 10 | * [Contributing](#contributing) 11 | * [License](#license) 12 | 13 | Discord: [https://discord.gg/d3Qk65J](https://discord.gg/d3Qk65J) 14 | 15 | ## Kapitel 1 16 | 17 | Eine Einführung in V mit einfachen Beispielen und Aufgaben. 18 | 19 | * [Hello World](examples/section_1/hello_world.md) 20 | * [V Schlüsselwörter](examples/section_1/keywords.md) 21 | * [Primitives](examples/section_1/primitives.md) 22 | * [Variablen](examples/section_1/variables.md) 23 | * [Strings](examples/section_1/strings.md) 24 | * [Kommentare](examples/section_1/comment.md) 25 | 26 | ## Kapitel 2 27 | 28 | Dieses Kapitel behandelt bedingte Anweisungen, Schleifen und andere wichtige Operatoren in V. 29 | 30 | * [Operatoren](examples/section_2/operator.md) 31 | * [If-else](examples/section_2/if-else.md) 32 | * [Match](examples/section_2/match.md) 33 | * [Schleifen](examples/section_2/loops.md) 34 | 35 | ## Kaptiel 3 36 | 37 | Hier wird die wichtigste Datenstruktur in V behandelt: `Array`s und `Struct`s. Beinhaltet sind weiterhin Beispiele und Erklärungen zu den Themen Funktionen und Methoden. 38 | 39 | * [Funktionen](examples/section_3/functions.md) 40 | * [Arrays](examples/section_3/arrays.md) 41 | * [Struct](examples/section_3/struct.md) 42 | * [Methoden](examples/section_3/methods.md) 43 | 44 | ## Kapitel 4 45 | 46 | In diesem Kapitel werden Arrays noch einmal vertieft. Es wird hier auch auf das Format `JSON` eingegangen, der Bereich Dateioperationen \(lesen und schreiben\), sowie Testing gezeigt. 47 | 48 | * [Array Funktionen](examples/section_4/array-functions.md) 49 | * [Testing](examples/section_4/testing.md) 50 | * [File-IO](examples/section_4/files.md) 51 | * [JSON](examples/section_4/json.md) 52 | 53 | ## Team 54 | 55 | Derzeitige Liste der Autoren/Maintainer 56 | 57 | * [Don Alfons Nisnoni](https://github.com/dhonx) 58 | * [Ivo-Balbaert](https://github.com/ibalbaert) 59 | * [Sven Patrick Meier](https://github.com/SuicideS3ason) 60 | * [Swastik Baranwal](https://github.com/Delta456) 61 | * [Vitor Oliveira](https://github.com/vbrazo) 62 | 63 | ## Contributing 64 | 65 | Um etwas beizutragen einfach den [Contributing-Guide](CONTRIBUTING.md) lesen, die Schritte befolgen und los geht's! Wir wählen Maintainer aufgrund ihrer Beiträge zum Projekt aus. 66 | 67 | ## Lizenz 68 | 69 | [MIT](/LICENSE) 70 | -------------------------------------------------------------------------------- /de/examples/README.md: -------------------------------------------------------------------------------- 1 | # Examples 2 | -------------------------------------------------------------------------------- /de/examples/section_1/README.md: -------------------------------------------------------------------------------- 1 | # Section 1 2 | -------------------------------------------------------------------------------- /de/examples/section_1/comment.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Kommentare 4 | --- 5 | 6 | # Kommentare 7 | 8 | V bietet die Möglichkeit Zeilenkommentare mit `//` und mehrzeilige Kommentare mit `/* */` zu erzeugen. 9 | Kommentare sollen genutzt werden, um den Code zu dokumentieren, sodass andere verstehen können was dieser Teil des Codes tut. 10 | Kommentare in V können auch ineinander geschachtelt sein. 11 | 12 | ```v 13 | // Das ist ein Zeilenkommentar 14 | 15 | /* Das hier ist ein 16 | * mehrzeiliger Kommentar 17 | * /* Dieser Kommentar wurde in den mehrzeiligen Kommentar geschachtelt. */ 18 | */ 19 | ``` 20 | -------------------------------------------------------------------------------- /de/examples/section_1/hello_world.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Formatted Print 4 | --- 5 | 6 | # Formatted Print 7 | 8 | Konsolenausgaben werden durch verschiedene I/O-Streams gehandhabt, dazu sollte man wissen, wo und wie sie zu verwenden sind. 9 | 10 | - `print`: schreibt Text in den Standard output stream (stdout), ohne einen Zeilenumbruch am Ende. 11 | 12 | - `println`: wie `print`, allerdings mit Zeilenumbruch am Ende. 13 | 14 | - `eprint`: wie `print`, aber der Output geht durch den Standard Error Stream (stderr). 15 | 16 | - `eprintln`: wie `eprint`, aber mit einem Zeilenumbruch am Ende. 17 | 18 | - `panic`: gibt den übergebenen Text auf der Konsole aus und beendet das Programm mit Fehlerode 1. 19 | 20 | ```v 21 | print('Hello World') 22 | print('Hello V') 23 | ``` 24 | 25 | Dieses Programm erzeugt die folgende Ausgabe in der Konsole: `Hello WorldHello V` 26 | 27 | Wenn man die nächste Zeile in einer neuen Zeile ausgeben möchte, muss man am Ende des Satzes ein `\n` hinzufügen. 28 | 29 | ```v 30 | print('Hello World \n') 31 | print('Hello V ') 32 | ``` 33 | 34 | Wenn man `\n` nicht verwenden möchte, dann kann man statt `print` auch `println` verwenden. 35 | 36 | ## Exercises 37 | 38 | Entkommentiere den Code in `hello.v` und sieh was passiert. 39 | -------------------------------------------------------------------------------- /de/examples/section_1/keywords.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Schlüsselwörter 4 | --- 5 | 6 | # Schlüsselwörter 7 | 8 | V ist eine kleine Programmiersprache mit wenigen Schlüsselwörtern (circa 23 Stück). 9 | 10 | | Schlüsselwörter | der | Programmiersprache | V | | 11 | | --------------- | ------ | ------------------ | -------- | --------- | 12 | | break | const | as | continue | defer | 13 | | else | enum | fn | for | struct | 14 | | go | goto | if | import | return | 15 | | type | pub | mut | in | interface | 16 | | match | module | or | none | | 17 | 18 | Wie in anderen Programmiersprachen können Schlüsselwörter nicht als Variablenbezeichner verwendet werden. 19 | -------------------------------------------------------------------------------- /de/examples/section_1/primitives.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Datentypen 4 | --- 5 | 6 | # Primitive Datentypen 7 | 8 | V hat weniger primitive Datentypen als Go. 9 | 10 | ## Grundlegende Typen 11 | 12 | - `bool`: Wahrheitswert `true` oder `false` 13 | 14 | - `string`: eine Zeichenkette aus Bytes 15 | 16 | - `int`: numerischer Typ für ganze Zahlen 17 | 18 | - `float` numerischer Typ für Gleitkommazahlen. 19 | 20 | - `rune`: Unicode string, ein character literal 21 | 22 | ## Komplexere Typen 23 | 24 | - `array`/`[]`: Eine Sammlung von Elementen des selben Typs (siehe [Array](../section_3/arrays.md)). 25 | 26 | - `map`: Eine Sammlung von Schlüssel- und Wertpaaren `{ 'key' : value }` 27 | 28 | - `struct`: Eine Datenstruktur zur Modellierung komplexerer Daten (siehe [Structs](../section_3/struct.md)). 29 | 30 | ## Integer 31 | 32 | Der Typ Integer kann weiterhin unterschieden werden in `signed` und `unsigned`. `Signed` bedeutet vorzeichenbehaftet, also positive und negative Werte der Variable sind möglich. 33 | `Unsigned` hingegen hat kein Vorzeichen, demnach kann der Wert nur eine positive Zahl sein. 34 | 35 | ### Signed Integer 36 | 37 | | Type | Größe | Wertbereich | 38 | | ------ | :------: | ---------------------------------------: | 39 | | int8 | 8 bits | -128 bis 27 -1 | 40 | | int16 | 16 bits | -215 bis 215 - 1 | 41 | | int | 32 bits | -231 bis 231 - 1 | 42 | | int64 | 64 bits | -263 bis 263 - 1 | 43 | | int128 | 128 bits | -2127 bis 2127 - 1 | 44 | 45 | ### Unsigned Integer 46 | 47 | | Type | Size | Wertbereich | 48 | | ---- | :------: | ------------------------: | 49 | | byte | 8 bits | 0 bis 27 -1 | 50 | | u16 | 16 bits | 0 bis 215 - 1 | 51 | | u32 | 32 bits | 0 bis 231 - 1 | 52 | | u64 | 64 bits | 0 bis 263 - 1 | 53 | | u128 | 128 bits | 0 bis 2127 - 1 | 54 | -------------------------------------------------------------------------------- /de/examples/section_1/variables.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Variables 4 | --- 5 | 6 | # Variables 7 | 8 | Variablen können in V mit dem `:=` Operator deklariert und initialisiert werden. 9 | Das ist die einzige Möglichkeit Variablen in V zu erzeugen, daraus folgt, dass alle Variablen in V immer einen initialen Wert haben. 10 | Der Typ der Variable wird aus dem Wert auf der rechten Seite der Zuweisung abgeleitet. Variablen in V sind immutable per default. 11 | 12 | ```go 13 | age := 23 // int 14 | name := 'Alice' // string 15 | is_adult := age > 21 // bool 16 | 17 | println(age_str) // 23 18 | println(name) // Alice 19 | println(is_adult) // true 20 | ``` 21 | 22 | **Merke:** Variablen können nur innerhalb einer Funktion definiert werden. Es gibt in V keine globalen Variablen und auch keinen globalen Programmzustand. 23 | 24 | Um den Wert einer Variable zu ändern muss diese mutable sein. Dies kann durch hinzufügen von `mut` zur Deklaration erreicht werden. 25 | Einen neuen Variablenwert kann man dann mit `=` setzen. 26 | 27 | ```go 28 | mut age := 20 // we declare the mutable variable age and assign it to the value 20. 29 | println(age) // 20 30 | age = 21 // we assign a new value to age 31 | println(age) // 21 32 | ``` 33 | 34 | Das Weglassen des `mut` Schlüsselworts hier resultiert in einem Fehler beim Kompilieren, denn der Wert einer immutable Variable kann nicht verändert werden. 35 | 36 | ```go 37 | fn main() { 38 | age = 20 39 | println(age) 40 | } 41 | ``` 42 | 43 | Der obenstehende Code würde ebenfalls in einem Fehler beim kompilieren resultieren, da die Variable `age` hier nicht definiert ist, 44 | 45 | ```go 46 | fn main() { 47 | mut age := 20 // we declare the mutable variable age and assign it to the value 20. 48 | println(age) // 20 49 | age := 21 // ERROR 50 | } 51 | ``` 52 | 53 | Hier würde `age := 21` einen Fehler beim kompilieren erzeugen, denn `age` ist hier schon definiert und kann nicht neu deklariert werden. 54 | 55 | Eine Variable anlegen: `:=`. 56 | 57 | Einen neuen Wert zuweisen: `=`. 58 | -------------------------------------------------------------------------------- /de/examples/section_2/README.md: -------------------------------------------------------------------------------- 1 | # Section 2 2 | -------------------------------------------------------------------------------- /de/examples/section_2/if-else.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: If statement 4 | --- 5 | 6 | # If statement 7 | 8 | ## The `if` statement 9 | 10 | An `if` statement is a programming conditional statement that, if proved true, executes the code given in the block. Below is a general example of an if statement in V: 11 | 12 | ```go 13 | john_height := 100 14 | maria_height := 178 15 | 16 | if john_height < maria_height { 17 | println("Maria is taller than John") 18 | } 19 | ``` 20 | 21 | In the above code, `println()` will only execute when the condition is true. 22 | There are no parentheses needed for surrounding the condition, and the braces are always required. 23 | 24 | ## The `else` statement 25 | 26 | An `else` statement is a programming conditional statement in which when `if` evaluates to false then the code in `else` block executes. 27 | 28 | ```go 29 | joey_age := 12 30 | kevin_age := 15 31 | 32 | if joey_age > kevin_age { 33 | println("Joey is older") 34 | } else { 35 | println("Kevin is older") 36 | } 37 | ``` 38 | 39 | In this example, the code inside the `else` block will execute because the condition in `if` evaluates to `false`. 40 | 41 | ## The `else if` statement 42 | 43 | The `if...else` statement executes two different codes depending upon whether the test expression is `true` or `false`. Sometimes, a choice has to be made from more than 2 possibilities. The `if...else if...else` ladder allows you to check between multiple test expressions and execute different statements. 44 | 45 | ```go 46 | tom_age := 20 47 | ashia_age := 38 48 | 49 | if tom_age < ashia_age { 50 | println("Tom is younger than Ashia") 51 | } else if tom_age > ashia_age { 52 | println("Tom is older than Ashia") 53 | } else { 54 | println("Tom and Ashia are the same age") 55 | } 56 | ``` 57 | 58 | Output 59 | 60 | ``` 61 | Tom is younger than Asia 62 | ``` 63 | 64 | ## Nested `if..else` statement 65 | 66 | It is always a good practice to nest `if...else` statements which means you can use one `if`, `else` or `else...if` statement inside another `if` or `else...if` statement. 67 | 68 | ```go 69 | tom_age := 20 70 | ashia_age := 38 71 | 72 | if tom_age < ashia_age { 73 | if tom_age < 18 { 74 | println("tom_age < 18 and younger than Ashia.") 75 | } else { 76 | println("tom_age >= 18 and younger than Ashia.") 77 | } 78 | } else if tom_age > ashia_age { 79 | println("$tom_age > $ashia_age") 80 | } else { 81 | println("$tom_age == $ashia_age") 82 | } 83 | ``` 84 | 85 | Output 86 | 87 | ``` 88 | tom_age >= 18 and younger than Ashia. 89 | ``` 90 | 91 | ## Using `if..else` as expression 92 | 93 | The `if..else` can also be used as an expression: 94 | 95 | ```go 96 | tom_age := 20 97 | ashia_age := 38 98 | 99 | s := if tom_age < ashia_age { 100 | "Tom is the youngest" 101 | } else { 102 | "Ashia is the youngest" 103 | } 104 | 105 | print(s) 106 | ``` 107 | 108 | Output 109 | 110 | ``` 111 | Tom is the youngest 112 | ``` 113 | 114 | ## Exercises 115 | 116 | 1. Write a V program to accept two integers and check whether they are equal or not. 117 | 2. Write a V program to check whether a given number is even or odd. 118 | 3. Write a V program to check whether a given number is positive or negative. 119 | 4. Write a V program to find whether a given year is a leap year or not. 120 | -------------------------------------------------------------------------------- /de/examples/section_2/loops.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Looping Constructs 4 | --- 5 | 6 | # Looping Constructs 7 | 8 | There's only one type of loop in V language, like Go which can be used in many ways. 9 | 10 | ## `for` loop 11 | 12 | `for` loops offer a quick and easy way to do something repeatedly. 13 | They're handy, if you want to run the same code over and over again, each time with a different value. 14 | You can think of a loop as a computerized version of the game where you tell someone to take X steps in one direction then Y steps in another; 15 | for example, the idea "Go five steps to the east" could be expressed this way as a loop: 16 | 17 | ```go 18 | for i := 0; i < 5; i++ { 19 | println('Walking one step') 20 | } 21 | ``` 22 | 23 | V has the `for` looping construct and the loop can be written in different ways: 24 | 25 | 1. `in` operator for array/map 26 | 27 | ```go 28 | ages := [18, 25, 32, 43, 50] 29 | 30 | for age in ages { 31 | println(age) 32 | } 33 | ``` 34 | 35 | > Note: The value is read-only. 36 | 37 | 2. `for` loop with a condition 38 | 39 | This is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. 40 | There are no parentheses surrounding the condition, and the braces are always required. 41 | 42 | ```go 43 | mut factorial := 1 44 | mut counter := 1 45 | 46 | for { 47 | counter++ 48 | if counter > 5 { 49 | println(factorial) 50 | break 51 | } 52 | factorial = factorial * counter 53 | } 54 | 55 | println(counter) 56 | ``` 57 | 58 | Output 59 | 60 | ``` 61 | 120 62 | 6 63 | ``` 64 | 65 | A for loop with a break statement can always be made shorter by placing the inverse condition right after for, making it equivalent with the while statement in other languages. 66 | 67 | ```go 68 | mut factorial := 1 69 | mut counter := 1 70 | 71 | for counter <= 5 { 72 | factorial = factorial * counter 73 | counter++ 74 | } 75 | println(factorial) 76 | println(counter) 77 | ``` 78 | 79 | Output 80 | 81 | ``` 82 | 120 83 | 6 84 | ``` 85 | 86 | 3. Traditional C style 87 | 88 | ```go 89 | mut factorial := 1 90 | mut counter := 1 91 | 92 | for counter = 1; counter < 6; counter++ { 93 | factorial = factorial * counter 94 | if counter == 5 { 95 | print(factorial) 96 | continue 97 | } 98 | println(counter) 99 | } 100 | ``` 101 | 102 | 4. Infinite Loop 103 | 104 | `for` loop can also be infinite 105 | 106 | ```go 107 | for { 108 | println('foo') 109 | } 110 | ``` 111 | 112 | ## Exercises 113 | 114 | 1. Write a V program to display the first 10 natural numbers. 115 | 2. Write a V program to find the sum of first 10 natural numbers. 116 | 3. Write a V program to print the integers inside an array and also print their mean. 117 | 4. Write a V program to read 10 numbers from keyboard and find their sum and average. 118 | 5. Write a V program to display the cube of the number upto given an integer. 119 | -------------------------------------------------------------------------------- /de/examples/section_2/match.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Match 4 | --- 5 | 6 | # Match 7 | 8 | ## The `match` statement 9 | 10 | A match statement is a short-hand way for `if - else`. 11 | If the input is matched the statement block of the first matching branch will be executed and its last expression will be returned. 12 | The `else` branch will be executed when there is no other matching branch. 13 | 14 | ```v 15 | num := 1 16 | match num % 2 == 0 { 17 | true { print('The input number is even.') } 18 | else { print('The input number is odd.') } 19 | } 20 | ``` 21 | 22 | One can also initialize variables using `match` to have different values according to a condition. 23 | 24 | ```v 25 | num := 3 26 | s := match num { 27 | 1 { 'one' } 28 | 2 { 'two' } 29 | else { 30 | 'many' 31 | } 32 | } 33 | ``` 34 | 35 | Examples: 36 | 37 | ```v 38 | fn even(num int) bool { 39 | match num % 2 == 0 { 40 | true { print('The input number is even.') } 41 | else { print('The input number is odd.') } 42 | } 43 | } 44 | 45 | fn num_to_str(num int) int { 46 | match num { 47 | 1 { 'one' } 48 | 2 { 'two' } 49 | else { 50 | 'many' 51 | } 52 | } 53 | } 54 | 55 | fn main() { 56 | println(even(14)) // 'The input number is even.' 57 | println(even(3)) // 'The input number is odd.' 58 | println(num_to_str(1)) // 'one' 59 | println(num_to_str(2)) // 'two' 60 | println(num_to_str(352)) // 'many' 61 | } 62 | ``` 63 | 64 | ### Enums 65 | 66 | One can also match on `enum` values (variants) as branches by using the `.variant_here` syntax: 67 | 68 | ```v 69 | enum Animal { 70 | cat 71 | dog 72 | goldfish 73 | pig 74 | } 75 | 76 | fn makes_miau(a Animal) bool { 77 | return match a { 78 | .cat { true } 79 | else { false } 80 | } 81 | } 82 | 83 | fn is_land_creature(a Animal) bool { 84 | return match a { 85 | .cat { true } 86 | .dog { true } 87 | .pig { true } 88 | else { 89 | false 90 | } 91 | } 92 | } 93 | // OR LIKE THAT 94 | fn is_land_creature_alt(a Animal) bool { 95 | return match a { 96 | .goldfish { false } 97 | else { 98 | true 99 | } 100 | } 101 | } 102 | 103 | fn main() { 104 | my_cat := Animal.cat 105 | my_goldfish := Animal.goldfish 106 | 107 | println(makes_miau(my_cat)) // true 108 | println(is_land_creature(my_cat)) // true 109 | println(is_land_creature(my_goldfish)) // false 110 | } 111 | ``` 112 | 113 | ### Exercises 114 | 115 | 1. Write a V program that creates an array of all even numbers from 1 to 50. 116 | 2. Write a V program that, given an array of numbers, returns the maximum value. 117 | 3. Write a V program that determines whether color (enum) is red or blue 118 | -------------------------------------------------------------------------------- /de/examples/section_2/operator.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Operators 4 | --- 5 | 6 | # Operators 7 | 8 | V bietet die folgenden Operatoren: 9 | 10 | ## Grundlegende Operatoren 11 | 12 | - `+`: 13 | 14 | - Arithmetik: Addition von `int`, `float` 15 | - `string`-Konkatenation. 16 | 17 | - `-` Subtraktion von `int` und `float`. 18 | 19 | - `*` Multiplikation von `int` und `float`. 20 | 21 | - `/` Division von `int` und `float`. 22 | 23 | - `%` Modulo-operator: Ganzzahlige Teilung mit Rest `int`. 24 | 25 | - `=` Zuweisung eines Wertes für eine Variable. 26 | 27 | - `:=` Deklaration und Initialisierung einer Variable. 28 | 29 | ```v 30 | println(3 + 5) 31 | println(2.0 + 5.0) 32 | println('hello' + 'world') 33 | 34 | println(9 - 10) 35 | println(7.0 - 5.0) 36 | 37 | println(3 * 5) 38 | println(2.0 * 4) 39 | 40 | println(23 / 3) 41 | println(25.0 / 5.0) 42 | 43 | println(27 % 5) 44 | println(27 % 3) 45 | ``` 46 | 47 | Output 48 | 49 | ```v 50 | 8 51 | 7.0 52 | hello world 53 | 54 | -1 55 | 2.0 56 | 57 | 15 58 | 8.0 59 | 60 | 7 61 | 5.0 62 | 63 | 2 64 | 0 65 | ``` 66 | 67 | > Bemerkung: Im Gegensatz zu anderen (Programmier-) Sprachen kann der `Modulo`-operator (`%`) in V nicht mit `floats` angewandt werden. 68 | 69 | ## Vergleichsoperatoren 70 | 71 | - `>` größer als 72 | 73 | - `<` kleiner als 74 | 75 | - `==` gleich 76 | 77 | - `>=` größer oder gleich 78 | 79 | - `<=` kleiner oder gleich 80 | 81 | - `!=` ungleich 82 | 83 | ## Boolsche Operatoren 84 | 85 | - `&&` logisches und 86 | 87 | - `||` logisches oder 88 | 89 | - `!` logisches nicht 90 | 91 | ## Bitwise Operators 92 | 93 | - `<<` bitshift links 94 | 95 | - `>>` bitshift rechts 96 | 97 | - `&` bitweises Und 98 | 99 | - `|` bitweises Oder 100 | 101 | - `^` bitweises XOR (exklusives Oder) 102 | 103 | ## Zuweisungsoperatoren 104 | 105 | - `+=` ist äquivalent zu `foo = foo + var` 106 | 107 | - `-=` ist äquivalent zu `foo = foo - var` 108 | 109 | - `*=` ist äquivalent zu `foo = foo * var` 110 | 111 | - `/=` ist äquivalent zu `foo = foo / var` 112 | 113 | - `&=` ist äquivalent zu `foo = foo & var` 114 | 115 | - `|=` ist äquivalent zu `foo = foo | var` 116 | 117 | - `>>=` ist äquivalent zu `foo = foo >> var` 118 | 119 | - `<<=` ist äquivalent zu `foo = foo << var` 120 | 121 | ## Spezielle Operatoren 122 | 123 | - `in`: für eine Prüfung ob ein Element Teil einer Sammlung ist. 124 | 125 | - `none`: zur Prüfung, ob ein Wert gesetzt wurde. 126 | -------------------------------------------------------------------------------- /de/examples/section_3/README.md: -------------------------------------------------------------------------------- 1 | # Section 3 2 | -------------------------------------------------------------------------------- /de/examples/section_3/functions.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Functions 4 | --- 5 | 6 | # Functions 7 | 8 | A function is a block of organized, reusable code that is used to perform a single, related action. 9 | Functions provide better modularity for your application and a high degree of code reusing. 10 | 11 | Ideally, you should consider using the [single responsibility principle](https://en.wikipedia.org/wiki/Single_responsibility_principle) (SOLID) which states that every module or function should have responsibility 12 | for a single part of the functionality provided by the software to keep your code maintainable. 13 | 14 | Like C and Go, functions cannot be overloaded. 15 | 16 | ```go 17 | fn sum(x, y int) int { 18 | return x + y 19 | } 20 | 21 | println(sum(77, 33)) 22 | ``` 23 | 24 | > Note: The type comes after the argument's name. 25 | 26 | ```go 27 | fn full_name(first_name, last_name string) string { 28 | return first_name + ' ' + last_name 29 | } 30 | 31 | println(full_name("Vitor", "Oliveira")) 32 | ``` 33 | 34 | ## Variadic Functions 35 | 36 | Functions can also be variadic i.e. accept an infinite number of arguments. 37 | They are not arrays and cannot be returned. 38 | 39 | ```go 40 | fn foo(test ...string) { 41 | for txt in test { 42 | println(txt) 43 | } 44 | } 45 | 46 | foo("V", "is", "the", "best", "lang" , "ever") 47 | ``` 48 | 49 | Output 50 | 51 | ``` 52 | V 53 | is 54 | the 55 | best 56 | lang 57 | ever 58 | ``` 59 | 60 | ## Multi-Return Functions 61 | 62 | Similar to Go, functions in V can also return multiple and with a different type. 63 | 64 | ```go 65 | fn student(name string, age int) (string, int) { 66 | return name, age 67 | } 68 | 69 | name1, age1 := student("Tom", 15) 70 | println(name1) 71 | println(age1) 72 | ``` 73 | 74 | Output 75 | 76 | ``` 77 | Tom, 15 78 | ``` 79 | 80 | ## High Order Functions 81 | 82 | Functions in V can also take in another function as a parameter which is usually 83 | needed for something like sort, map, filter, etc. 84 | 85 | ```go 86 | fn square(num int) int { 87 | return num * num 88 | } 89 | 90 | fn run(value int, op fn(int) int) int { 91 | return op(value) 92 | } 93 | 94 | println(run(10, square)) 95 | ``` 96 | 97 | Output 98 | 99 | ``` 100 | 100 101 | ``` 102 | 103 | ## Exercises 104 | 105 | 1. Write a V program to find the square of any number using the function. 106 | 2. Write a V program to check a given number is even or odd using the function. 107 | 3. Write a V program to convert decimal number to binary number using the function. 108 | 4. Write a V program to check whether a number is a prime number or not using the function. 109 | 5. Write a V program to get the largest element of an array using the function. 110 | -------------------------------------------------------------------------------- /de/examples/section_3/methods.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Methods 4 | --- 5 | 6 | # Methods 7 | 8 | V does not have classes. But one can define methods for types. 9 | A method is a function that has a special receiver argument, 10 | only a receiver of the specified type can execute this function. 11 | The receiver has its own argument list between `fn` and the method name. 12 | 13 | ```go 14 | struct User { 15 | name string 16 | email string 17 | mut: 18 | age int 19 | } 20 | 21 | fn (u User) can_register() bool { 22 | return u.age > 15 23 | } 24 | 25 | fn (u mut User) has_birthday() { 26 | u.age += 1 27 | } 28 | 29 | fn main() { 30 | mut bob := User { 31 | name: 'Bob' 32 | email: 'bob@bob.com' 33 | age: 15 34 | } 35 | alice := User { 36 | name: 'Alice' 37 | email: 'alice@alice-mail.com' 38 | age: 17 39 | } 40 | println(bob.can_register()) // false 41 | println('Bob needs to be 16 to register, but he only is ${bob.age}.') // Bob needs to be 16 to register, but he only is 15. 42 | println(alice.can_register()) // true 43 | bob.has_birthday() 44 | println(bob.age) // 16 45 | } 46 | ``` 47 | 48 | This code above realizes two methods for receivers `u` of type `User`. 49 | Note that the method `has_birthday()` has a `mut` receiver, this is needed here since we want to change its data. 50 | The convention of V is not to use receiver names like `self`, `this` or similar things but a short, preferably one letter long, name. 51 | 52 | ## Exercises 53 | 54 | 1. Create a method for the type `Person` that determines whether a person is underage or not. 55 | 2. Create a method that determines whether an `Animal` has fur or not. 56 | -------------------------------------------------------------------------------- /de/examples/section_3/struct.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Struct 4 | --- 5 | 6 | # Struct 7 | 8 | A struct is a composite data type (or record) declaration that defines a physically grouped list of variables under one name in a block of memory, allowing different variables to be accessed via a single pointer or by the struct declared name which returns the same address. 9 | 10 | For people coming from [OOP](https://en.wikipedia.org/wiki/Object-oriented_programming) languages, it can be thought as `class` but with more restrictions. 11 | 12 | ```go 13 | struct User { 14 | name string 15 | email string 16 | country string 17 | } 18 | 19 | fn main() { 20 | user := User { 21 | name: "V developers" 22 | email: "developers@vlang.io" 23 | country: "Canada" 24 | } 25 | 26 | println(user.country) 27 | } 28 | ``` 29 | 30 | > Note: Structs are allocated on the stack. 31 | 32 | You can use a comma to separate each field when creating a new instance of the struct. It's useful when you want to create a new instance on a single line. 33 | 34 | ```go 35 | user := User { name: "V developers", email: "developers@vlang.io", country: "Canada" } 36 | ``` 37 | 38 | ## The `&` prefix 39 | 40 | You can allocate a struct on the heap and get a reference to it by using the `&` prefix as follows: 41 | 42 | ```go 43 | user := &User{"V developers", "developers@vlang.io", "Canada"} 44 | println(user.name) 45 | ``` 46 | 47 | The type of `user` is `&User`. It's a reference to `User`. 48 | 49 | ## Access modifiers 50 | 51 | Struct fields are `private` and `immutable` by default. Their access modifiers can be changed with `pub` and `mut`. 52 | 53 | ```go 54 | struct User { 55 | email string 56 | } 57 | ``` 58 | 59 | You can define them as `private mutable`. 60 | 61 | ```go 62 | struct User { 63 | email string 64 | mut: 65 | first_name string 66 | last_name string 67 | } 68 | ``` 69 | 70 | You can also define them as `public immmutable` (readonly). 71 | 72 | ```go 73 | struct User { 74 | email string 75 | mut: 76 | first_name string 77 | last_name string 78 | pub: 79 | sin_number int 80 | } 81 | ``` 82 | 83 | or as `public`, but `mutable` only in the parent module. 84 | 85 | ```go 86 | struct User { 87 | email string 88 | mut: 89 | first_name string 90 | last_name string 91 | pub: 92 | sin_number int 93 | pub mut: 94 | phone int 95 | } 96 | ``` 97 | 98 | or `public` and `mutable` both inside and outside parent module. 99 | 100 | ```go 101 | struct User { 102 | email string 103 | mut: 104 | first_name string 105 | last_name string 106 | pub: 107 | sin_number int 108 | pub mut: 109 | phone int 110 | pub mut mut: 111 | address_1 string 112 | address_2 string 113 | city string 114 | country string 115 | zip string 116 | } 117 | ``` 118 | 119 | ## Exercises 120 | 121 | 1. Create a struct that stores and displays `User` information. 122 | 2. Create a `Point` struct that holds `x` and `y` field and guard them with private and public. 123 | -------------------------------------------------------------------------------- /de/examples/section_4/README.md: -------------------------------------------------------------------------------- 1 | # Section 4 2 | -------------------------------------------------------------------------------- /de/examples/section_4/array-functions.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Array Functions 4 | --- 5 | 6 | # Array Functions 7 | 8 | ## `repeat` 9 | 10 | Syntax 11 | 12 | ```go 13 | array.repeat(number int) 14 | ``` 15 | 16 | Makes an array with the given element number of times. 17 | 18 | ```go 19 | foo := [1, 2].repeat(5) 20 | println(foo) 21 | ``` 22 | 23 | Output 24 | 25 | ``` 26 | [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] 27 | ``` 28 | 29 | ## `delete` 30 | 31 | Syntax 32 | 33 | ```go 34 | array.delete(ix int) 35 | ``` 36 | 37 | Deletes the element present in the array at index `ix`. 38 | 39 | ```go 40 | mut even_numbers := [2, 4, 6, 8, 10] 41 | even_numbers.delete(3) 42 | println(even_numbers) 43 | ``` 44 | 45 | Output 46 | 47 | ``` 48 | [2, 4, 6, 10] 49 | ``` 50 | 51 | ## `reverse` 52 | 53 | Syntax 54 | 55 | ```go 56 | array.reverse() 57 | ``` 58 | 59 | Reverses the array. 60 | 61 | ```go 62 | float_num := [1.1, 1.3, 1.25, 1.4] 63 | float_num.reverse() 64 | ``` 65 | 66 | Output 67 | 68 | ``` 69 | [1.4, 1.25, 1.3, 1.1] 70 | ``` 71 | 72 | ## `clone` 73 | 74 | Syntax 75 | 76 | ```go 77 | array.clone() 78 | ``` 79 | 80 | Clones and returns a new array. 81 | 82 | ```go 83 | foo := [1, 2, 4, 5, 4, 6] 84 | foo1 := foo.clone() 85 | println(foo1) 86 | ``` 87 | 88 | Output 89 | 90 | ``` 91 | [1, 2, 4, 5, 4, 6] 92 | ``` 93 | -------------------------------------------------------------------------------- /de/examples/section_4/files.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Files 4 | --- 5 | 6 | # Files 7 | 8 | A File in V is an abstraction of any file object accessible by the program and is closely associated with `os` library. 9 | 10 | ## Reading Files 11 | 12 | Reading a file is an important task to tackle several different problems in computer science. In order to accomplish this task you can use the V native library `os` as described below: 13 | 14 | ```go 15 | import os 16 | 17 | fn main() { 18 | mut fp := flag.new_flag_parser(os.args) 19 | generator := fp.string('generator', '', 'generator name') 20 | method := fp.string('method', '', 'generator method name') 21 | path := './data/$generator/$method' 22 | 23 | if os.file_exists(path) { 24 | print_generator_sample(path) 25 | } else { 26 | println('File does not exist') 27 | return 28 | } 29 | } 30 | 31 | fn print_generator_sample(path string) { 32 | contents := os.read_file(path.trim_space()) or { 33 | println('Failed to open $path') 34 | return 35 | } 36 | 37 | lines := contents.split_into_lines() 38 | length := lines.len 39 | 40 | print_random_element(lines, length) 41 | } 42 | 43 | fn print_random_element(lines []string, length int) { 44 | rand.seed(time.now().uni) 45 | 46 | println(lines[rand.next(length-1)]) 47 | } 48 | ``` 49 | 50 | ## Writing files 51 | 52 | Writing files in V is similar to read files. 53 | 54 | ```go 55 | import os 56 | 57 | fn main() { 58 | path := './data/file.txt' 59 | text := 'Full text description.' 60 | 61 | if contents := os.write_file(path, text) or { 62 | println('Failed while creating file') 63 | return 64 | } 65 | 66 | content_lines = read_file(path) 67 | print(content_lines) 68 | } 69 | 70 | fn read_file(path string) { 71 | contents := os.read_file(path.trim_space()) or { 72 | println('Failed to open $path') 73 | return 74 | } 75 | 76 | return contents.split_into_lines() 77 | } 78 | ``` 79 | 80 | ## Exercises 81 | 82 | 1. Write a V program to create a new file with content. 83 | 2. Write a V program to read 2 different files and display their content. 84 | 3. Read how the `os` library works in V and understand how you could use it. 85 | 4. Encode a nested json string and write a new file with the result. 86 | -------------------------------------------------------------------------------- /de/examples/section_4/json.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: JSON 4 | --- 5 | 6 | # JSON 7 | 8 | JavaScript Object Notation (JSON) is a lightweight data-interchange format that is easy for humans to read and write. Furthermore, equally simple for machines to generate and/or parse. 9 | JSON is completely language agnostic and that's why it's the ideal interchange format. 10 | 11 | To read more about JSON visit: [json.org](http://json.org). 12 | 13 | ## Parsing JSON 14 | 15 | To parse a JSON string received by another application or generated within your existing application: 16 | 17 | ```go 18 | import json 19 | 20 | struct Customer { 21 | first_name string 22 | last_name string 23 | hometown string 24 | } 25 | 26 | fn main() { 27 | customers_string := '[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro" }, { "first_name": "Don", "last_name": "Nisnoni", "hometown": "Kupang" }]' 28 | customers := json.decode([]Customer, customers_string) or { 29 | eprintln('Failed to parse json') 30 | return 31 | } 32 | 33 | // Print the list of customers 34 | for customer in customers { 35 | println('$customer.first_name $customer.last_name: $customer.hometown') 36 | } 37 | } 38 | ``` 39 | 40 | ## Generating JSON 41 | 42 | Creating a JSON string for communication or serialization is just as simple. We decode and encode in the example below: 43 | 44 | ```go 45 | import json 46 | 47 | struct Customer { 48 | first_name string 49 | last_name string 50 | hometown string 51 | } 52 | 53 | fn main() { 54 | customer_string := '[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro"}]' 55 | 56 | customer := json.decode([]Customer, customer_string) or { 57 | eprintln('Failed to parse json') 58 | return 59 | } 60 | 61 | encoded_json := json.encode(customer) 62 | 63 | println(encoded_json) 64 | } 65 | ``` 66 | 67 | ## Exercises 68 | 69 | 1. Compare how you handle JSON in your favorite language and V. 70 | 2. Build an `Address` struct that contains address information. 71 | 3. Use the `Address` struct to decode and encode a string that contains JSON format. 72 | 4. Create 2 structs: `Address` and `User` where a user has many addresses. Now receive a string with a nested JSON like `'[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro", "addresses": [{ street_name: "Rua Princesa Isabel", city: "Rio de Janeiro", country: "Brazil" }] }]'`, decode and encode it. 73 | -------------------------------------------------------------------------------- /de/examples/section_4/testing.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Testing 4 | --- 5 | 6 | # Testing 7 | 8 | Testing in software development is a process that aims to evaluate the functionality of an application with an intent to find whether the code met the specified requirements or not as well as identifying the problems to ensure that the product has expected quality. 9 | 10 | ## Automated tests 11 | 12 | Automated tests follow the process of testing the software using an automation tool to find the defects. In this process, programmers execute the test scripts and generate the test results automatically by using automation tools. 13 | 14 | ## Tests in V 15 | 16 | In V, all test files have to be named with the following format: `*_test.v` and the functions should start with `test_*`. 17 | 18 | ```go 19 | // sum.v in subfolder sum 20 | module sum 21 | 22 | pub fn sum(a, b int) int { 23 | return a + b 24 | } 25 | ``` 26 | 27 | ```go 28 | // sum_test.v 29 | import sum 30 | 31 | fn test_sum() { 32 | assert sum.sum(2, 3) == 5 33 | // assert sum.sum(2, 3) == 777 // => sum_test.v:6: FAILED assertion 34 | } 35 | ``` 36 | 37 | To execute the test, you should run `v test_sum.v`. 38 | 39 | ### Examples 40 | 41 | 1. Testing JSON structures: 42 | 43 | ```go 44 | import json 45 | 46 | fn test_encode_customer(){ 47 | customer := Customer{ first_name: "Vitor", last_name: "Oliveira" } 48 | expected := '{ "first_name": "Vitor", "last_name": "Oliveira" }' 49 | 50 | encoded_json := json.encode(customer) 51 | assert encoded_json == expected 52 | } 53 | ``` 54 | 55 | 2. Testing files: 56 | 57 | ```go 58 | import os 59 | 60 | fn test_file_creation() { 61 | file_name := './new_file.txt' 62 | content := 'text' 63 | 64 | os.write_file(file_name, content) 65 | assert content.len == os.file_size(file_name) 66 | 67 | os.rm(file_name) 68 | } 69 | ``` 70 | -------------------------------------------------------------------------------- /docs_style_guide.md: -------------------------------------------------------------------------------- 1 | # Documentation Style Guide 2 | 3 | These are the guidelines for writing documentation. 4 | 5 | ## Titles 6 | 7 | - Each page must have a single `#`-level title at the top. 8 | - Chapters in the same page must have `##`-level titles. 9 | - Sub-chapters need to increase the number of `#` in the title according to 10 | their nesting depth. 11 | - All words in the page's title must be capitalized, except for conjunctions 12 | like "of" and "and" . 13 | - Only the first word of a chapter title must be capitalized. 14 | 15 | ```markdown 16 | # Arrays 17 | 18 | ... 19 | 20 | ## How to declare an array 21 | 22 | ... 23 | 24 | ## Create an empty array 25 | 26 | ... 27 | ``` 28 | 29 | ## Print Width 30 | 31 | To be easy to read when editing the markdown code, if the sentence is too long, divide it down. 32 | The recommended column length limit is 80. 33 | 34 | ## Code Output 35 | 36 | To create output from code, there are two rules: 37 | 38 | - If the output is short then put it as a comment 39 | 40 | - If the output is quite long (column) then write it in a separate section after the code section. 41 | 42 | ## Indentation 43 | 44 | Indentation must use spaces and the tab size must be 4. 45 | -------------------------------------------------------------------------------- /en/examples/section_1/README.md: -------------------------------------------------------------------------------- 1 | # Section 1 2 | -------------------------------------------------------------------------------- /en/examples/section_1/comment.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Comments 4 | --- 5 | 6 | # Comments 7 | 8 | V supports single line comments `//` and multi-line comments `/* */`. 9 | They should be used for documenting the code for letting the other users know how the code works. 10 | It can also be used for temporarily commenting the code which has to be used later on. 11 | 12 | ```v 13 | // This is a single line comment 14 | 15 | /* This is a 16 | * multi-line comment 17 | * /* This could be nested as well*/ 18 | */ 19 | ``` 20 | -------------------------------------------------------------------------------- /en/examples/section_1/hello_world.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Hello World 4 | --- 5 | 6 | # Formatted Print 7 | 8 | Printing is handled by various I/O stream functions. One should know where to use them accordingly. 9 | 10 | - `print`: for printing the text to the output stream without a newline. 11 | 12 | - `println`: same as `print` but newline appended automatically. 13 | 14 | - `eprint`: same as `print` but the output goes to error stream (stderr). 15 | 16 | - `eprintln`: same as `println` but the output goes to error stream (stderr). 17 | 18 | - `panic`: outputs and exits from the program. 19 | 20 | ```v 21 | print('Hello World') 22 | print('Hello V') 23 | ``` 24 | 25 | This will print `Hello WorldHello V` 26 | 27 | If you want to print the next line on a new line you would have to do `\n`. 28 | 29 | ```v 30 | print('Hello World \n') 31 | print('Hello V ') 32 | ``` 33 | 34 | If you don't want to use `\n` then you can use `println` instead. 35 | 36 | ## Comments 37 | 38 | V supports single line comments `//` and multi-line comments `/* */`. 39 | They should be used for documenting the code for letting the other users know how the code works. 40 | It can also be used for temporarily commenting the code which has to be used later on. 41 | 42 | ```v 43 | // This is a single line comment 44 | 45 | /* This is a 46 | * multi-line comment 47 | * /* This could be nested as well*/ 48 | */ 49 | ``` 50 | 51 | ## Exercises 52 | 53 | Try uncommenting the code in `hello.v` and see what happens. 54 | -------------------------------------------------------------------------------- /en/examples/section_1/keywords.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Keywords 4 | --- 5 | 6 | # Keywords 7 | 8 | V is a very small language so it has few keywords. There are around 25 keywords. 9 | 10 | | Keywords | in | V | Programming | Language | 11 | | -------- | ------ | --- | ----------- | --------- | 12 | | break | const | as | continue | defer | 13 | | else | enum | fn | for | struct | 14 | | go | goto | if | import | return | 15 | | type | pub | mut | in | interface | 16 | | match | module | or | none | | 17 | 18 | Like other languages, they cannot be used as a variable. 19 | -------------------------------------------------------------------------------- /en/examples/section_1/primitives.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Primitives 4 | --- 5 | 6 | # Primitives 7 | 8 | V has less primitive types than Go. 9 | 10 | ## Basic Types 11 | 12 | - bool either `true` or `false` 13 | 14 | - string 15 | 16 | - integer type `int` 17 | 18 | - float type `float` 19 | 20 | - rune (Unicode string) 21 | 22 | ## Compound Types 23 | 24 | - arrays `[]` 25 | 26 | - map `{}` 27 | 28 | - struct 29 | 30 | ## Integer 31 | 32 | Integer is sub-classified into `signed` and `unsigned`. `signed` means positive or negative and `unsigned` means positive only. 33 | 34 | ### Signed Integer 35 | 36 | | Type | Size | Range | 37 | | ------ | :------: | --------------------------------------: | 38 | | int8 | 8 bits | -128 to 27 -1 | 39 | | int16 | 16 bits | -215 to 215 - 1 | 40 | | int | 32 bits | -231 to 231 - 1 | 41 | | int64 | 64 bits | -263 to 263 - 1 | 42 | | int128 | 128 bits | -2127 to 2127 - 1 | 43 | 44 | ### Unsigned Integer 45 | 46 | | Type | Size | Range | 47 | | ---- | :------: | -----------------------: | 48 | | byte | 8 bits | 0 to 27 -1 | 49 | | u16 | 16 bits | 0 to 215 - 1 | 50 | | u32 | 32 bits | 0 to 231 - 1 | 51 | | u64 | 64 bits | 0 to 263 - 1 | 52 | | u128 | 128 bits | 0 to 2127 - 1 | 53 | -------------------------------------------------------------------------------- /en/examples/section_1/strings.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Strings 4 | --- 5 | 6 | # Strings 7 | 8 | In V one can define strings using the `:=` operator. Strings (like other variables) are immutable by default. One is free to use `""` or `''` to denote a string. When using `vfmt` all double-quoted strings will be converted to single-quoted ones unless it contains a single quote character. 9 | 10 | ```go 11 | name := 'Bob' 12 | println(name) // Bob 13 | println(name.len) // 3 14 | ``` 15 | 16 | Getting the length of a string works with `.len`. 17 | 18 | ## Interpolation 19 | 20 | It is possible to do string interpolation with `$` in front of the variable: 21 | 22 | ```go 23 | name := 'Bob' 24 | println('Hello $name!') // Hello Bob! 25 | ``` 26 | 27 | One can have more complex expressions with interpolation syntax by using `${}`: 28 | 29 | ```go 30 | struct User { 31 | name string 32 | age int 33 | } 34 | bob := User { 35 | name: 'Bob' 36 | age: 17 37 | } 38 | println('Say Hello to a new User: ${bob.name}, ${bob.age}') // Say Hello to new User: Bob, 17 39 | println('${bob.name}s age is higher or equal to 18: ${bob.age >= 18}') // 0 <=> number representation for false 40 | ``` 41 | 42 | ## Concatenation 43 | 44 | Strings can be concatenated with the `+` operator. 45 | 46 | ```go 47 | text := 'Hello' 48 | concatenated_text := text + ' World!' 49 | println(text) // Hello 50 | println(text + ' World!') // Hello World! 51 | println(concatenated_text) // Hello World! 52 | ``` 53 | 54 | Appending to a string works with concatenation as well as with `+=` operator. Since strings are immutable by default it is only possible to do this if they are declared with `mut`. 55 | 56 | ```go 57 | mut hello := 'Hello ' 58 | hello += 'from V!' // appends 'from V!' to the string stored in hello. 59 | println(hello) // Hello from V! 60 | ``` 61 | 62 | In V, string data is encoded using UTF-8 and the string itself is a read-only array of bytes. This makes slicing possible, which means we can access single-character literals or slices of a string variable. 63 | 64 | ```go 65 | robert := 'Robert' 66 | bert := robert[2..robert.len] // bert 67 | rob := robert[0..3] // Rob 68 | println('The persons of interest are: $robert, $bert, $rob') // The persons of interest are: Robert, bert, Rob 69 | ``` 70 | 71 | ### Notes 72 | 73 | When using `some_string[start..end]` syntax the `end` is **not** inclusive. 74 | 75 | All operators in V must have values of the same type on both sides. The code below will not compile because `age` is an `int`: 76 | 77 | ```go 78 | age := 25 79 | println('age = ' + age) 80 | ``` 81 | 82 | We therefore need to convert it to string by using `.str()` or use string interpolation (preferred): 83 | 84 | ```go 85 | age := 25 86 | println('age = ' + age.str()) // age = 25 87 | println('age = $age') // age = 25 88 | ``` 89 | 90 | To define character literals use: ` `` `. Raw strings can be defined as prepending `r`. They are not escaped. 91 | 92 | ```go 93 | hello := 'Hello\nWorld' 94 | println(hello) // Hello 95 | // World 96 | raw_hello := r'Hello\nWorld' 97 | println(raw_hello) // Hello\nWorld 98 | ``` 99 | -------------------------------------------------------------------------------- /en/examples/section_1/variables.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Variables 4 | --- 5 | 6 | # Variables 7 | 8 | In V variables can be declared and initialized with the `:=` operator. Variables can only be declared this way in V, this means all variables have an initial value. The type of a variable is inferred from the value on the right hand side. By default variables in V are immutable. 9 | 10 | ```go 11 | age := 23 // int 12 | name := 'Alice' // string 13 | is_adult := age > 21 // bool 14 | 15 | println(age_str) // 23 16 | println(name) // Alice 17 | println(is_adult) // true 18 | ``` 19 | 20 | > Note: Variables can only be defined in a function. There are no global variables and no global state in V. 21 | 22 | To change the value of a variable, it needs to be mutable. This can be done using the `mut` keyword when declaring the variable. To assign a new value to a variable use `=`. 23 | 24 | ```go 25 | mut age := 20 // declare the mutable variable age and assign it to the value 20. 26 | println(age) // 20 27 | age = 21 // assign a new value to age 28 | println(age) // 21 29 | ``` 30 | 31 | Leaving out the `mut` keyword here would result in an error because the value of an immutable variable cannot be changed. 32 | 33 | ```go 34 | fn main() { 35 | age = 20 36 | println(age) 37 | } 38 | ``` 39 | 40 | The code above would result in an error during compilation because the variable `age` is not declared, 41 | 42 | ```go 43 | fn main() { 44 | mut age := 20 // we declare the mutable variable age and assign it to the value 20. 45 | println(age) // 20 46 | age := 21 // ERROR 47 | } 48 | ``` 49 | 50 | here `age := 21` will result in another error while compiling because the variable `age` is already defined in the scope. It's very simple to remember, just declare value with `:=` and assign value with `=`. 51 | 52 | Like Go, You can also use `_` for ignoring values when it is not needed. Usually used in multi return functions. 53 | 54 | ```go 55 | _ := "I don't need this value" 56 | println(_) // ERROR: Cannot use `_` as value 57 | ``` 58 | 59 | ## Naming Rules 60 | 61 | The following are the rules which should be kept in mind while naming variables. 62 | 63 | - Name should not contain Uppercase letters like `AlphaTest` 64 | - Use underscores as separators like `hello_world` 65 | - Name should be descriptive as possible 66 | - Name should not contain `__` 67 | - Name should not contain any space 68 | - If the name is longer than 11 then it must use `_` as separator 69 | 70 | These rules are from [`Snake_Case`](https://en.wikipedia.org/wiki/Snake_case). V uses Snake Case and prefers it because it is more easy to read, write and understand. 71 | 72 | ### Valid Names 73 | 74 | ```go 75 | boby 76 | john_dads 77 | myfamily_number 78 | ``` 79 | 80 | ### Invalid Names 81 | 82 | ```go 83 | IamNotValid 84 | new Make 85 | ``` 86 | -------------------------------------------------------------------------------- /en/examples/section_2/README.md: -------------------------------------------------------------------------------- 1 | # Section 2 2 | -------------------------------------------------------------------------------- /en/examples/section_2/loops.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Loops 4 | --- 5 | 6 | # Looping Constructs 7 | 8 | There's only one type of loop in V language, like Go which can be used in many ways. 9 | 10 | ## `for` loop 11 | 12 | `for` loops offer a quick and easy way to do something repeatedly. 13 | They're handy, if you want to run the same code over and over again, each time with a different value. 14 | You can think of a loop as a computerized version of the game where you tell someone to take X steps in one direction then Y steps in another; 15 | for example, the idea "Go five steps to the east" could be expressed this way as a loop: 16 | 17 | ```go 18 | for i := 0; i < 5; i++ { 19 | println('Walking one step') 20 | } 21 | ``` 22 | 23 | V has the `for` looping construct and the loop can be written in different ways: 24 | 25 | - `in` operator for array/map 26 | 27 | ```go 28 | ages := [18, 25, 32, 43, 50] 29 | 30 | for age in ages { 31 | println(age) 32 | } 33 | ``` 34 | 35 | > Note: The value is read-only. 36 | 37 | - `for` loop with a condition 38 | 39 | This is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. 40 | There are no parentheses surrounding the condition, and the braces are always required. 41 | 42 | ```go 43 | mut factorial := 1 44 | mut counter := 1 45 | 46 | for { 47 | counter++ 48 | if counter > 5 { 49 | println(factorial) 50 | break 51 | } 52 | factorial = factorial * counter 53 | } 54 | 55 | println(counter) 56 | ``` 57 | 58 | Output 59 | 60 | ```console 61 | 120 62 | 6 63 | ``` 64 | 65 | A for loop with a break statement can always be made shorter by placing the inverse condition right after for, making it equivalent with the while statement in other languages. 66 | 67 | ```go 68 | mut factorial := 1 69 | mut counter := 1 70 | 71 | for counter <= 5 { 72 | factorial = factorial * counter 73 | counter++ 74 | } 75 | println(factorial) 76 | println(counter) 77 | ``` 78 | 79 | Output 80 | 81 | ```console 82 | 120 83 | 6 84 | ``` 85 | 86 | - Traditional C style 87 | 88 | ```go 89 | mut factorial := 1 90 | mut counter := 1 91 | 92 | for counter = 1; counter < 6; counter++ { 93 | factorial = factorial * counter 94 | if counter == 5 { 95 | print(factorial) 96 | continue 97 | } 98 | println(counter) 99 | } 100 | ``` 101 | 102 | - Infinite Loop 103 | 104 | `for` loop can also be infinite 105 | 106 | ```go 107 | for { 108 | println('foo') 109 | } 110 | ``` 111 | 112 | ## Exercises 113 | 114 | 1. Write a V program to display the first 10 natural numbers. 115 | 2. Write a V program to find the sum of first 10 natural numbers. 116 | 3. Write a V program to print the integers inside an array and also print their mean. 117 | 4. Write a V program to read 10 numbers from keyboard and find their sum and average. 118 | 5. Write a V program to display the cube of the number upto given an integer. 119 | -------------------------------------------------------------------------------- /en/examples/section_2/match.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Match 4 | --- 5 | 6 | # Match 7 | 8 | ## The `match` statement 9 | 10 | A match statement is a short-hand way for `if - else`. 11 | If the input is matched the statement block of the first matching branch will be executed and its last expression will be returned. 12 | The `else` branch will be executed when there is no other matching branch. 13 | 14 | ```v 15 | num := 1 16 | match num % 2 == 0 { 17 | true { print('The input number is even.') } 18 | else { print('The input number is odd.') } 19 | } 20 | ``` 21 | 22 | One can also initialize variables using `match` to have different values according to a condition. 23 | 24 | ```v 25 | num := 3 26 | s := match num { 27 | 1 { 'one' } 28 | 2 { 'two' } 29 | else { 30 | 'many' 31 | } 32 | } 33 | ``` 34 | 35 | Examples: 36 | 37 | ```v 38 | fn even(num int) bool { 39 | match num % 2 == 0 { 40 | true { print('The input number is even.') } 41 | else { print('The input number is odd.') } 42 | } 43 | } 44 | 45 | fn num_to_str(num int) int { 46 | match num { 47 | 1 { 'one' } 48 | 2 { 'two' } 49 | else { 50 | 'many' 51 | } 52 | } 53 | } 54 | 55 | fn main() { 56 | println(even(14)) // 'The input number is even.' 57 | println(even(3)) // 'The input number is odd.' 58 | println(num_to_str(1)) // 'one' 59 | println(num_to_str(2)) // 'two' 60 | println(num_to_str(352)) // 'many' 61 | } 62 | ``` 63 | 64 | ### Enums 65 | 66 | One can also match on `enum` values (variants) as branches by using the `.variant_here` syntax: 67 | 68 | ```v 69 | enum Animal { 70 | cat 71 | dog 72 | goldfish 73 | pig 74 | } 75 | 76 | fn makes_miau(a Animal) bool { 77 | return match a { 78 | .cat { true } 79 | else { false } 80 | } 81 | } 82 | 83 | fn is_land_creature(a Animal) bool { 84 | return match a { 85 | .cat { true } 86 | .dog { true } 87 | .pig { true } 88 | else { 89 | false 90 | } 91 | } 92 | } 93 | // OR LIKE THAT 94 | fn is_land_creature_alt(a Animal) bool { 95 | return match a { 96 | .goldfish { false } 97 | else { 98 | true 99 | } 100 | } 101 | } 102 | 103 | fn main() { 104 | my_cat := Animal.cat 105 | my_goldfish := Animal.goldfish 106 | 107 | println(makes_miau(my_cat)) // true 108 | println(is_land_creature(my_cat)) // true 109 | println(is_land_creature(my_goldfish)) // false 110 | } 111 | ``` 112 | 113 | ### Exercises 114 | 115 | 1. Write a V program that creates an array of all even numbers from 1 to 50. 116 | 2. Write a V program that, given an array of numbers, returns the maximum value. 117 | 3. Write a V program that determines whether color (enum) is red or blue 118 | -------------------------------------------------------------------------------- /en/examples/section_2/operator.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Operators 4 | --- 5 | 6 | # Operators 7 | 8 | V supports the following operators: 9 | 10 | ## Basic Operators 11 | 12 | - `+` (addition) for int, float and string 13 | 14 | - `-` (subtraction) for int and float 15 | 16 | - `*` (multiplication) for int and float 17 | 18 | - `/` (division) for int and float 19 | 20 | - `%` (modulos) for int 21 | 22 | - `=` (assignment) for changing values 23 | 24 | - `:=` for initialising values 25 | 26 | ```v 27 | println(3 + 5) 28 | println(2.0 + 5.0) 29 | println('hello' + 'world') 30 | 31 | println(9 - 10) 32 | println(7.0 - 5.0) 33 | 34 | println(3 * 5) 35 | println(2.0 * 4) 36 | 37 | println(23 / 3) 38 | println(25.0 / 5.0) 39 | 40 | println(27 % 5) 41 | println(27 % 3) 42 | ``` 43 | 44 | Output 45 | 46 | ```v 47 | 8 48 | 7.0 49 | hello world 50 | 51 | -1 52 | 2.0 53 | 54 | 15 55 | 8.0 56 | 57 | 7 58 | 5.0 59 | 60 | 2 61 | 0 62 | ``` 63 | 64 | > Note: Unlike other languages, V doesn't allow modulus with float. 65 | 66 | ## Comparison Operators 67 | 68 | - `>` greater than 69 | 70 | - `<` lesser than 71 | 72 | - `==` equal to 73 | 74 | - `>=` greater than or equal to 75 | 76 | - `<=` lesser than or equal to 77 | 78 | - `!=` not equal to 79 | 80 | ## Boolean Operators 81 | 82 | - `&&` and 83 | 84 | - `||` or 85 | 86 | - `!` not 87 | 88 | ## Bitwise Operators 89 | 90 | - `<<` left bitshift 91 | 92 | - `>>` right bitshift 93 | 94 | - `&` bitwise and 95 | 96 | - `|` bitwise or 97 | 98 | - `^` bitwise xor 99 | 100 | ## Assignments Operators 101 | 102 | - `+=` same as `foo = foo + var` 103 | 104 | - `-=` same as `foo = foo - var` 105 | 106 | - `*=` same as `foo = foo * var` 107 | 108 | - `/=` same as `foo = foo / var` 109 | 110 | - `&=` same as `foo = foo & var` 111 | 112 | - `|=` same as `foo = foo | var` 113 | 114 | - `>>=` same as `foo = foo >> var` 115 | 116 | - `<<=` same as `foo = foo << var` 117 | 118 | ## Special Operators 119 | 120 | - `in` for membership 121 | 122 | - `none` for optional 123 | -------------------------------------------------------------------------------- /en/examples/section_3/README.md: -------------------------------------------------------------------------------- 1 | # Section 3 2 | -------------------------------------------------------------------------------- /en/examples/section_3/methods.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Methods 4 | --- 5 | 6 | # Methods 7 | 8 | V does not have classes. But one can define methods for types. 9 | A method is a function that has a special receiver argument, 10 | only a receiver of the specified type can execute this function. 11 | The receiver has its own argument list between `fn` and the method name. 12 | 13 | ```go 14 | struct User { 15 | name string 16 | email string 17 | mut: 18 | age int 19 | } 20 | 21 | fn (u User) can_register() bool { 22 | return u.age > 15 23 | } 24 | 25 | fn (u mut User) has_birthday() { 26 | u.age += 1 27 | } 28 | 29 | fn main() { 30 | mut bob := User { 31 | name: 'Bob' 32 | email: 'bob@bob.com' 33 | age: 15 34 | } 35 | alice := User { 36 | name: 'Alice' 37 | email: 'alice@alice-mail.com' 38 | age: 17 39 | } 40 | println(bob.can_register()) 41 | println("Bob needs to be 16 to register, but he only is ${bob.age}.") 42 | println(alice.can_register()) 43 | bob.has_birthday() 44 | println(bob.age) 45 | } 46 | ``` 47 | 48 | Output 49 | 50 | ```console 51 | false 52 | Bob needs to be 16 to register, but he only is 15. 53 | true 54 | 16 55 | ``` 56 | 57 | This code above realizes two methods for receivers `u` of type `User`. 58 | Note that the method `has_birthday()` has a `mut` receiver, this is needed here since we want to change its data. 59 | The convention of V is not to use receiver names like `self`, `this` or similar things but a short, preferably one letter long, name. 60 | 61 | ## Exercises 62 | 63 | 1. Create a method for the type `Person` that determines whether a person is underage or not. 64 | 2. Create a method that determines whether an `Animal` has fur or not. 65 | -------------------------------------------------------------------------------- /en/examples/section_4/README.md: -------------------------------------------------------------------------------- 1 | # Section 4 2 | -------------------------------------------------------------------------------- /en/examples/section_4/array-functions.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Array Functions 4 | --- 5 | 6 | # Array Functions 7 | 8 | ## `repeat` 9 | 10 | Syntax 11 | 12 | ```go 13 | array.repeat(number type) 14 | ``` 15 | 16 | Makes an array with the given element number of times. 17 | 18 | ```go 19 | foo := [1, 2].repeat(5) 20 | println(foo) // [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] 21 | ``` 22 | 23 | ## `delete` 24 | 25 | Syntax 26 | 27 | ```go 28 | array.delete(ix type) 29 | ``` 30 | 31 | Deletes the element present in the array at index `ix`. 32 | 33 | ```go 34 | mut even_numbers := [2, 4, 6, 8, 10] 35 | even_numbers.delete(3) 36 | println(even_numbers) // [2, 4, 6, 10] 37 | ``` 38 | 39 | ## `reverse` 40 | 41 | Syntax 42 | 43 | ```go 44 | array.reverse() 45 | ``` 46 | 47 | Reverses the array. 48 | 49 | ```go 50 | float_num := [1.1, 1.3, 1.25, 1.4] 51 | float_num.reverse() // [1.4, 1.25, 1.3, 1.1] 52 | ``` 53 | 54 | ## `clone` 55 | 56 | Syntax 57 | 58 | ```go 59 | array.clone() 60 | ``` 61 | 62 | Clones and returns a new array. 63 | 64 | ```go 65 | foo := [1, 2, 4, 5, 4, 6] 66 | foo1 := foo.clone() 67 | println(foo1) // [1, 2, 4, 5, 4, 6] 68 | ``` 69 | -------------------------------------------------------------------------------- /en/examples/section_4/files.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Files 4 | --- 5 | 6 | # Files 7 | 8 | A File in V is an abstraction of any file object accessible by the program and is closely associated with `os` library. 9 | 10 | ## Reading Files 11 | 12 | Reading a file is an important task to tackle several different problems in computer science. In order to accomplish this task you can use the V native library `os` as described below: 13 | 14 | ```go 15 | import os 16 | 17 | fn main() { 18 | mut fp := flag.new_flag_parser(os.args) 19 | generator := fp.string('generator', '', 'generator name') 20 | method := fp.string('method', '', 'generator method name') 21 | path := './data/$generator/$method' 22 | 23 | if os.file_exists(path) { 24 | print_generator_sample(path) 25 | } else { 26 | println('File does not exist') 27 | return 28 | } 29 | } 30 | 31 | fn print_generator_sample(path string) { 32 | contents := os.read_file(path.trim_space()) or { 33 | println('Failed to open $path') 34 | return 35 | } 36 | 37 | lines := contents.split_into_lines() 38 | length := lines.len 39 | 40 | print_random_element(lines, length) 41 | } 42 | 43 | fn print_random_element(lines []string, length int) { 44 | rand.seed(time.now().uni) 45 | 46 | println(lines[rand.next(length-1)]) 47 | } 48 | ``` 49 | 50 | ## Writing files 51 | 52 | Writing files in V is similar to read files. 53 | 54 | ```go 55 | import os 56 | 57 | fn main() { 58 | path := './data/file.txt' 59 | text := 'Full text description.' 60 | 61 | if contents := os.write_file(path, text) or { 62 | println('Failed while creating file') 63 | return 64 | } 65 | 66 | content_lines = read_file(path) 67 | print(content_lines) 68 | } 69 | 70 | fn read_file(path string) { 71 | contents := os.read_file(path.trim_space()) or { 72 | println('Failed to open $path') 73 | return 74 | } 75 | 76 | return contents.split_into_lines() 77 | } 78 | ``` 79 | 80 | ## Exercises 81 | 82 | 1. Write a V program to create a new file with content. 83 | 2. Write a V program to read 2 different files and display their content. 84 | 3. Read how the `os` library works in V and understand how you could use it. 85 | 4. Encode a nested json string and write a new file with the result. 86 | -------------------------------------------------------------------------------- /en/examples/section_4/json.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: JSON 4 | --- 5 | 6 | # JSON 7 | 8 | JavaScript Object Notation (JSON) is a lightweight data-interchange format that is easy for humans to read and write. Furthermore, equally simple for machines to generate and/or parse. 9 | JSON is completely language agnostic and that's why it's the ideal interchange format. 10 | 11 | To read more about JSON visit: [json.org](http://json.org). 12 | 13 | ## Parsing JSON 14 | 15 | To parse a JSON string received by another application or generated within your existing application: 16 | 17 | ```go 18 | import json 19 | 20 | struct Customer { 21 | first_name string 22 | last_name string 23 | hometown string 24 | } 25 | 26 | fn main() { 27 | customers_string := '[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro" }, { "first_name": "Don", "last_name": "Nisnoni", "hometown": "Kupang" }]' 28 | customers := json.decode([]Customer, customers_string) or { 29 | eprintln('Failed to parse json') 30 | return 31 | } 32 | 33 | // Print the list of customers 34 | for customer in customers { 35 | println('$customer.first_name $customer.last_name: $customer.hometown') 36 | } 37 | } 38 | ``` 39 | 40 | ## Generating JSON 41 | 42 | Creating a JSON string for communication or serialization is just as simple. We decode and encode in the example below: 43 | 44 | ```go 45 | import json 46 | 47 | struct Customer { 48 | first_name string 49 | last_name string 50 | hometown string 51 | } 52 | 53 | fn main() { 54 | customer_string := '[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro"}]' 55 | 56 | customer := json.decode([]Customer, customer_string) or { 57 | eprintln('Failed to parse json') 58 | return 59 | } 60 | 61 | encoded_json := json.encode(customer) 62 | 63 | println(encoded_json) 64 | } 65 | ``` 66 | 67 | ## Exercises 68 | 69 | 1. Compare how you handle JSON in your favorite language and V. 70 | 2. Build an `Address` struct that contains address information. 71 | 3. Use the `Address` struct to decode and encode a string that contains JSON format. 72 | 4. Create 2 structs: `Address` and `User` where a user has many addresses. Now receive a string with a nested JSON like `'[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro", "addresses": [{ street_name: "Rua Princesa Isabel", city: "Rio de Janeiro", country: "Brazil" }] }]'`, decode and encode it. 73 | -------------------------------------------------------------------------------- /en/examples/section_4/testing.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Testing 4 | --- 5 | 6 | # Testing 7 | 8 | Testing in software development is a process that aims to evaluate the functionality of an application with an intent to find whether the code met the specified requirements or not as well as identifying the problems to ensure that the product has expected quality. 9 | 10 | ## Automated tests 11 | 12 | Automated tests follow the process of testing the software using an automation tool to find the defects. In this process, programmers execute the test scripts and generate the test results automatically by using automation tools. 13 | 14 | ## Tests in V 15 | 16 | In V, all test files have to be named with the following format: `*_test.v` and the functions should start with `test_*`. 17 | 18 | ```go 19 | // sum.v in subfolder sum 20 | module sum 21 | 22 | pub fn sum(a, b int) int { 23 | return a + b 24 | } 25 | ``` 26 | 27 | ```go 28 | // sum_test.v 29 | import sum 30 | 31 | fn test_sum() { 32 | assert sum.sum(2, 3) == 5 33 | // assert sum.sum(2, 3) == 777 // => sum_test.v:6: FAILED assertion 34 | } 35 | ``` 36 | 37 | To execute the test, you should run `v test_sum.v`. 38 | 39 | ### Examples 40 | 41 | 1. Testing JSON structures: 42 | 43 | ```go 44 | import json 45 | 46 | fn test_encode_customer(){ 47 | customer := Customer{ first_name: "Vitor", last_name: "Oliveira" } 48 | expected := '{ "first_name": "Vitor", "last_name": "Oliveira" }' 49 | 50 | encoded_json := json.encode(customer) 51 | assert encoded_json == expected 52 | } 53 | ``` 54 | 55 | 2. Testing files: 56 | 57 | ```go 58 | import os 59 | 60 | fn test_file_creation() { 61 | file_name := './new_file.txt' 62 | content := 'text' 63 | 64 | os.write_file(file_name, content) 65 | assert content.len == os.file_size(file_name) 66 | 67 | os.rm(file_name) 68 | } 69 | ``` 70 | -------------------------------------------------------------------------------- /fr/section_1/Beinvenue_monde.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | titre de l'example: Hello World 4 | --- 5 | 6 | # imprimé formaté 7 | 8 | L'impression est assurée par diverses fonctions de flux I/O. Il convient de savoir où les utiliser en conséquence. 9 | 10 | - `print`: pour l'impression du texte dans le flux de sortie sans nouvelle ligne. 11 | 12 | - `println`: la même que `print` mais nouvelle ligne ajoutée automatiquement. 13 | 14 | - `eprint`: la même que `print` mais le résultat est transmis au flux d'erreurs (stderr). 15 | 16 | - `eprintln`: la même que `println` mais le résultat est transmis au flux d'erreurs (stderr). 17 | 18 | - `panic`: fait une production et sort du programme. 19 | 20 | ```v 21 | print('Hello World') 22 | print('Hello V') 23 | ``` 24 | 25 | Il sera imprimé ce qui suit `Hello WorldHello V` 26 | 27 | Si vous souhaitez imprimer la ligne suivante sur une nouvelle ligne, vous devrez faire `\n`. 28 | 29 | ```v 30 | print('Hello World \n') 31 | print('Hello V ') 32 | ``` 33 | 34 | si vous ne voulez pas utiliser `\n` alors vous utilisez `println` au lieu de cela. 35 | 36 | ## Les commentaires 37 | 38 | V soutient les commentaires d'une seule ligne `//` et les commentaires de plusieurs lignes `/* */`. 39 | Ils doivent être utilisés pour documenter le code afin de faire savoir aux autres utilisateurs comment le code fonctionne. Il peut également être utilisé pour commenter temporairement le code qui doit être utilisé par la suite. 40 | 41 | ```v 42 | // Ceci est un commentaire d'une seule ligne 43 | 44 | /* Ceci est un 45 | * commentaire de plusiers lignes 46 | * /* Elle peut également être imbriquée*/ 47 | */ 48 | ``` 49 | 50 | ## Exercises 51 | 52 | Essayez de décommenter le code en `hello.v` et voyez ce qui se passe. 53 | -------------------------------------------------------------------------------- /fr/section_1/README.md: -------------------------------------------------------------------------------- 1 | # Section 1 2 | -------------------------------------------------------------------------------- /fr/section_1/les_chaînes de caractères.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Strings 4 | --- 5 | 6 | # Strings 7 | 8 | In V one can define strings using the `:=` operator. Strings (like other variables) are immutable by default. One is free to use `""` or `''` to denote a string. When using `vfmt` all double-quoted strings will be converted to single-quoted ones unless it contains a single quote character. 9 | 10 | ```go 11 | name := 'Bob' 12 | println(name) // Bob 13 | println(name.len) // 3 14 | ``` 15 | 16 | Getting the length of a string works with `.len`. 17 | 18 | ## Interpolation 19 | 20 | It is possible to do string interpolation with `$` in front of the variable: 21 | 22 | ```go 23 | name := 'Bob' 24 | println('Hello $name!') // Hello Bob! 25 | ``` 26 | 27 | One can have more complex expressions with interpolation syntax by using `${}`: 28 | 29 | ```go 30 | struct User { 31 | name string 32 | age int 33 | } 34 | bob := User { 35 | name: 'Bob' 36 | age: 17 37 | } 38 | println('Say Hello to a new User: ${bob.name}, ${bob.age}') // Say Hello to new User: Bob, 17 39 | println('${bob.name}s age is higher or equal to 18: ${bob.age >= 18}') // 0 <=> number representation for false 40 | ``` 41 | 42 | ## Concatenation 43 | 44 | Strings can be concatenated with the `+` operator. 45 | 46 | ```go 47 | text := 'Hello' 48 | concatenated_text := text + ' World!' 49 | println(text) // Hello 50 | println(text + ' World!') // Hello World! 51 | println(concatenated_text) // Hello World! 52 | ``` 53 | 54 | Appending to a string works with concatenation as well as with `+=` operator. Since strings are immutable by default it is only possible to do this if they are declared with `mut`. 55 | 56 | ```go 57 | mut hello := 'Hello ' 58 | hello += 'from V!' // appends 'from V!' to the string stored in hello. 59 | println(hello) // Hello from V! 60 | ``` 61 | 62 | In V, string data is encoded using UTF-8 and the string itself is a read-only array of bytes. This makes slicing possible, which means we can access single-character literals or slices of a string variable. 63 | 64 | ```go 65 | robert := 'Robert' 66 | bert := robert[2..robert.len] // bert 67 | rob := robert[0..3] // Rob 68 | println('The persons of interest are: $robert, $bert, $rob') // The persons of interest are: Robert, bert, Rob 69 | ``` 70 | 71 | ### Notes 72 | 73 | When using `some_string[start..end]` syntax the `end` is **not** inclusive. 74 | 75 | All operators in V must have values of the same type on both sides. The code below will not compile because `age` is an `int`: 76 | 77 | ```go 78 | age := 25 79 | println('age = ' + age) 80 | ``` 81 | 82 | We therefore need to convert it to string by using `.str()` or use string interpolation (preferred): 83 | 84 | ```go 85 | age := 25 86 | println('age = ' + age.str()) // age = 25 87 | println('age = $age') // age = 25 88 | ``` 89 | 90 | To define character literals use: ` `` `. Raw strings can be defined as prepending `r`. They are not escaped. 91 | 92 | ```go 93 | hello := 'Hello\nWorld' 94 | println(hello) // Hello 95 | // World 96 | raw_hello := r'Hello\nWorld' 97 | println(raw_hello) // Hello\nWorld 98 | ``` 99 | -------------------------------------------------------------------------------- /fr/section_1/les_commentaires.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Comments 4 | --- 5 | 6 | # Comments 7 | 8 | V supports single line comments `//` and multi-line comments `/* */`. 9 | They should be used for documenting the code for letting the other users know how the code works. 10 | It can also be used for temporarily commenting the code which has to be used later on. 11 | 12 | ```v 13 | // This is a single line comment 14 | 15 | /* This is a 16 | * multi-line comment 17 | * /* This could be nested as well*/ 18 | */ 19 | ``` 20 | -------------------------------------------------------------------------------- /fr/section_1/les_mots_clés.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Keywords 4 | --- 5 | 6 | # Keywords 7 | 8 | V is a very small language so it has few keywords. There are around 25 keywords. 9 | 10 | | Keywords | in | V | Programming | Language | 11 | | -------- | ------ | --- | ----------- | --------- | 12 | | break | const | as | continue | defer | 13 | | else | enum | fn | for | struct | 14 | | go | goto | if | import | return | 15 | | type | pub | mut | in | interface | 16 | | match | module | or | none | | 17 | 18 | Like other languages, they cannot be used as a variable. 19 | -------------------------------------------------------------------------------- /fr/section_1/les_primitives.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Primitives 4 | --- 5 | 6 | # Primitives 7 | 8 | V has less primitive types than Go. 9 | 10 | ## Basic Types 11 | 12 | - bool either `true` or `false` 13 | 14 | - string 15 | 16 | - integer type `int` 17 | 18 | - float type `float` 19 | 20 | - rune (Unicode string) 21 | 22 | ## Compound Types 23 | 24 | - arrays `[]` 25 | 26 | - map `{}` 27 | 28 | - struct 29 | 30 | ## Integer 31 | 32 | Integer is sub-classified into `signed` and `unsigned`. `signed` means positive or negative and `unsigned` means positive only. 33 | 34 | ### Signed Integer 35 | 36 | | Type | Size | Range | 37 | | ------ | :------: | --------------------------------------: | 38 | | int8 | 8 bits | -128 to 27 -1 | 39 | | int16 | 16 bits | -215 to 215 - 1 | 40 | | int | 32 bits | -231 to 231 - 1 | 41 | | int64 | 64 bits | -263 to 263 - 1 | 42 | | int128 | 128 bits | -2127 to 2127 - 1 | 43 | 44 | ### Unsigned Integer 45 | 46 | | Type | Size | Range | 47 | | ---- | :------: | -----------------------: | 48 | | byte | 8 bits | 0 to 27 -1 | 49 | | u16 | 16 bits | 0 to 215 - 1 | 50 | | u32 | 32 bits | 0 to 231 - 1 | 51 | | u64 | 64 bits | 0 to 263 - 1 | 52 | | u128 | 128 bits | 0 to 2127 - 1 | 53 | -------------------------------------------------------------------------------- /fr/section_1/les_variables.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Variables 4 | --- 5 | 6 | # Variables 7 | 8 | In V variables can be declared and initialized with the `:=` operator. Variables can only be declared this way in V, this means all variables have an initial value. The type of a variable is inferred from the value on the right hand side. By default variables in V are immutable. 9 | 10 | ```go 11 | age := 23 // int 12 | name := 'Alice' // string 13 | is_adult := age > 21 // bool 14 | 15 | println(age_str) // 23 16 | println(name) // Alice 17 | println(is_adult) // true 18 | ``` 19 | 20 | > Note: Variables can only be defined in a function. There are no global variables and no global state in V. 21 | 22 | To change the value of a variable, it needs to be mutable. This can be done using the `mut` keyword when declaring the variable. To assign a new value to a variable use `=`. 23 | 24 | ```go 25 | mut age := 20 // declare the mutable variable age and assign it to the value 20. 26 | println(age) // 20 27 | age = 21 // assign a new value to age 28 | println(age) // 21 29 | ``` 30 | 31 | Leaving out the `mut` keyword here would result in an error because the value of an immutable variable cannot be changed. 32 | 33 | ```go 34 | fn main() { 35 | age = 20 36 | println(age) 37 | } 38 | ``` 39 | 40 | The code above would result in an error during compilation because the variable `age` is not declared, 41 | 42 | ```go 43 | fn main() { 44 | mut age := 20 // we declare the mutable variable age and assign it to the value 20. 45 | println(age) // 20 46 | age := 21 // ERROR 47 | } 48 | ``` 49 | 50 | here `age := 21` will result in another error while compiling because the variable `age` is already defined in the scope. It's very simple to remember, just declare value with `:=` and assign value with `=`. 51 | 52 | Like Go, You can also use `_` for ignoring values when it is not needed. Usually used in multi return functions. 53 | 54 | ```go 55 | _ := "I don't need this value" 56 | println(_) // ERROR: Cannot use `_` as value 57 | ``` 58 | 59 | ## Naming Rules 60 | 61 | The following are the rules which should be kept in mind while naming variables. 62 | 63 | - Name should not contain Uppercase letters like `AlphaTest` 64 | - Use underscores as separators like `hello_world` 65 | - Name should be descriptive as possible 66 | - Name should not contain `__` 67 | - Name should not contain any space 68 | - If the name is longer than 11 then it must use `_` as separator 69 | 70 | These rules are from [`Snake_Case`](https://en.wikipedia.org/wiki/Snake_case). V uses Snake Case and prefers it because it is more easy to read, write and understand. 71 | 72 | ### Valid Names 73 | 74 | ```go 75 | boby 76 | john_dads 77 | myfamily_number 78 | ``` 79 | 80 | ### Invalid Names 81 | 82 | ```go 83 | IamNotValid 84 | new Make 85 | ``` 86 | -------------------------------------------------------------------------------- /fr/section_2/README.md: -------------------------------------------------------------------------------- 1 | # Section 2 2 | -------------------------------------------------------------------------------- /fr/section_2/loops.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Loops 4 | --- 5 | 6 | # Looping Constructs 7 | 8 | There's only one type of loop in V language, like Go which can be used in many ways. 9 | 10 | ## `for` loop 11 | 12 | `for` loops offer a quick and easy way to do something repeatedly. 13 | They're handy, if you want to run the same code over and over again, each time with a different value. 14 | You can think of a loop as a computerized version of the game where you tell someone to take X steps in one direction then Y steps in another; 15 | for example, the idea "Go five steps to the east" could be expressed this way as a loop: 16 | 17 | ```go 18 | for i := 0; i < 5; i++ { 19 | println('Walking one step') 20 | } 21 | ``` 22 | 23 | V has the `for` looping construct and the loop can be written in different ways: 24 | 25 | - `in` operator for array/map 26 | 27 | ```go 28 | ages := [18, 25, 32, 43, 50] 29 | 30 | for age in ages { 31 | println(age) 32 | } 33 | ``` 34 | 35 | > Note: The value is read-only. 36 | 37 | - `for` loop with a condition 38 | 39 | This is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. 40 | There are no parentheses surrounding the condition, and the braces are always required. 41 | 42 | ```go 43 | mut factorial := 1 44 | mut counter := 1 45 | 46 | for { 47 | counter++ 48 | if counter > 5 { 49 | println(factorial) 50 | break 51 | } 52 | factorial = factorial * counter 53 | } 54 | 55 | println(counter) 56 | ``` 57 | 58 | Output 59 | 60 | ```console 61 | 120 62 | 6 63 | ``` 64 | 65 | A for loop with a break statement can always be made shorter by placing the inverse condition right after for, making it equivalent with the while statement in other languages. 66 | 67 | ```go 68 | mut factorial := 1 69 | mut counter := 1 70 | 71 | for counter <= 5 { 72 | factorial = factorial * counter 73 | counter++ 74 | } 75 | println(factorial) 76 | println(counter) 77 | ``` 78 | 79 | Output 80 | 81 | ```console 82 | 120 83 | 6 84 | ``` 85 | 86 | - Traditional C style 87 | 88 | ```go 89 | mut factorial := 1 90 | mut counter := 1 91 | 92 | for counter = 1; counter < 6; counter++ { 93 | factorial = factorial * counter 94 | if counter == 5 { 95 | print(factorial) 96 | continue 97 | } 98 | println(counter) 99 | } 100 | ``` 101 | 102 | - Infinite Loop 103 | 104 | `for` loop can also be infinite 105 | 106 | ```go 107 | for { 108 | println('foo') 109 | } 110 | ``` 111 | 112 | ## Exercises 113 | 114 | 1. Write a V program to display the first 10 natural numbers. 115 | 2. Write a V program to find the sum of first 10 natural numbers. 116 | 3. Write a V program to print the integers inside an array and also print their mean. 117 | 4. Write a V program to read 10 numbers from keyboard and find their sum and average. 118 | 5. Write a V program to display the cube of the number upto given an integer. 119 | -------------------------------------------------------------------------------- /fr/section_2/match.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Match 4 | --- 5 | 6 | # Match 7 | 8 | ## The `match` statement 9 | 10 | A match statement is a short-hand way for `if - else`. 11 | If the input is matched the statement block of the first matching branch will be executed and its last expression will be returned. 12 | The `else` branch will be executed when there is no other matching branch. 13 | 14 | ```v 15 | num := 1 16 | match num % 2 == 0 { 17 | true { print('The input number is even.') } 18 | else { print('The input number is odd.') } 19 | } 20 | ``` 21 | 22 | One can also initialize variables using `match` to have different values according to a condition. 23 | 24 | ```v 25 | num := 3 26 | s := match num { 27 | 1 { 'one' } 28 | 2 { 'two' } 29 | else { 30 | 'many' 31 | } 32 | } 33 | ``` 34 | 35 | Examples: 36 | 37 | ```v 38 | fn even(num int) bool { 39 | match num % 2 == 0 { 40 | true { print('The input number is even.') } 41 | else { print('The input number is odd.') } 42 | } 43 | } 44 | 45 | fn num_to_str(num int) int { 46 | match num { 47 | 1 { 'one' } 48 | 2 { 'two' } 49 | else { 50 | 'many' 51 | } 52 | } 53 | } 54 | 55 | fn main() { 56 | println(even(14)) // 'The input number is even.' 57 | println(even(3)) // 'The input number is odd.' 58 | println(num_to_str(1)) // 'one' 59 | println(num_to_str(2)) // 'two' 60 | println(num_to_str(352)) // 'many' 61 | } 62 | ``` 63 | 64 | ### Enums 65 | 66 | One can also match on `enum` values (variants) as branches by using the `.variant_here` syntax: 67 | 68 | ```v 69 | enum Animal { 70 | cat 71 | dog 72 | goldfish 73 | pig 74 | } 75 | 76 | fn makes_miau(a Animal) bool { 77 | return match a { 78 | .cat { true } 79 | else { false } 80 | } 81 | } 82 | 83 | fn is_land_creature(a Animal) bool { 84 | return match a { 85 | .cat { true } 86 | .dog { true } 87 | .pig { true } 88 | else { 89 | false 90 | } 91 | } 92 | } 93 | // OR LIKE THAT 94 | fn is_land_creature_alt(a Animal) bool { 95 | return match a { 96 | .goldfish { false } 97 | else { 98 | true 99 | } 100 | } 101 | } 102 | 103 | fn main() { 104 | my_cat := Animal.cat 105 | my_goldfish := Animal.goldfish 106 | 107 | println(makes_miau(my_cat)) // true 108 | println(is_land_creature(my_cat)) // true 109 | println(is_land_creature(my_goldfish)) // false 110 | } 111 | ``` 112 | 113 | ### Exercises 114 | 115 | 1. Write a V program that creates an array of all even numbers from 1 to 50. 116 | 2. Write a V program that, given an array of numbers, returns the maximum value. 117 | 3. Write a V program that determines whether color (enum) is red or blue 118 | -------------------------------------------------------------------------------- /fr/section_2/operator.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Operators 4 | --- 5 | 6 | # Operators 7 | 8 | V supports the following operators: 9 | 10 | ## Basic Operators 11 | 12 | - `+` (addition) for int, float and string 13 | 14 | - `-` (subtraction) for int and float 15 | 16 | - `*` (multiplication) for int and float 17 | 18 | - `/` (division) for int and float 19 | 20 | - `%` (modulos) for int 21 | 22 | - `=` (assignment) for changing values 23 | 24 | - `:=` for initialising values 25 | 26 | ```v 27 | println(3 + 5) 28 | println(2.0 + 5.0) 29 | println('hello' + 'world') 30 | 31 | println(9 - 10) 32 | println(7.0 - 5.0) 33 | 34 | println(3 * 5) 35 | println(2.0 * 4) 36 | 37 | println(23 / 3) 38 | println(25.0 / 5.0) 39 | 40 | println(27 % 5) 41 | println(27 % 3) 42 | ``` 43 | 44 | Output 45 | 46 | ```v 47 | 8 48 | 7.0 49 | hello world 50 | 51 | -1 52 | 2.0 53 | 54 | 15 55 | 8.0 56 | 57 | 7 58 | 5.0 59 | 60 | 2 61 | 0 62 | ``` 63 | 64 | > Note: Unlike other languages, V doesn't allow modulus with float. 65 | 66 | ## Comparison Operators 67 | 68 | - `>` greater than 69 | 70 | - `<` lesser than 71 | 72 | - `==` equal to 73 | 74 | - `>=` greater than or equal to 75 | 76 | - `<=` lesser than or equal to 77 | 78 | - `!=` not equal to 79 | 80 | ## Boolean Operators 81 | 82 | - `&&` and 83 | 84 | - `||` or 85 | 86 | - `!` not 87 | 88 | ## Bitwise Operators 89 | 90 | - `<<` left bitshift 91 | 92 | - `>>` right bitshift 93 | 94 | - `&` bitwise and 95 | 96 | - `|` bitwise or 97 | 98 | - `^` bitwise xor 99 | 100 | ## Assignments Operators 101 | 102 | - `+=` same as `foo = foo + var` 103 | 104 | - `-=` same as `foo = foo - var` 105 | 106 | - `*=` same as `foo = foo * var` 107 | 108 | - `/=` same as `foo = foo / var` 109 | 110 | - `&=` same as `foo = foo & var` 111 | 112 | - `|=` same as `foo = foo | var` 113 | 114 | - `>>=` same as `foo = foo >> var` 115 | 116 | - `<<=` same as `foo = foo << var` 117 | 118 | ## Special Operators 119 | 120 | - `in` for membership 121 | 122 | - `none` for optional 123 | -------------------------------------------------------------------------------- /fr/section_3/README.md: -------------------------------------------------------------------------------- 1 | # Section 3 2 | -------------------------------------------------------------------------------- /fr/section_3/methods.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Methods 4 | --- 5 | 6 | # Methods 7 | 8 | V does not have classes. But one can define methods for types. 9 | A method is a function that has a special receiver argument, 10 | only a receiver of the specified type can execute this function. 11 | The receiver has its own argument list between `fn` and the method name. 12 | 13 | ```go 14 | struct User { 15 | name string 16 | email string 17 | mut: 18 | age int 19 | } 20 | 21 | fn (u User) can_register() bool { 22 | return u.age > 15 23 | } 24 | 25 | fn (u mut User) has_birthday() { 26 | u.age += 1 27 | } 28 | 29 | fn main() { 30 | mut bob := User { 31 | name: 'Bob' 32 | email: 'bob@bob.com' 33 | age: 15 34 | } 35 | alice := User { 36 | name: 'Alice' 37 | email: 'alice@alice-mail.com' 38 | age: 17 39 | } 40 | println(bob.can_register()) 41 | println("Bob needs to be 16 to register, but he only is ${bob.age}.") 42 | println(alice.can_register()) 43 | bob.has_birthday() 44 | println(bob.age) 45 | } 46 | ``` 47 | 48 | Output 49 | 50 | ```console 51 | false 52 | Bob needs to be 16 to register, but he only is 15. 53 | true 54 | 16 55 | ``` 56 | 57 | This code above realizes two methods for receivers `u` of type `User`. 58 | Note that the method `has_birthday()` has a `mut` receiver, this is needed here since we want to change its data. 59 | The convention of V is not to use receiver names like `self`, `this` or similar things but a short, preferably one letter long, name. 60 | 61 | ## Exercises 62 | 63 | 1. Create a method for the type `Person` that determines whether a person is underage or not. 64 | 2. Create a method that determines whether an `Animal` has fur or not. 65 | -------------------------------------------------------------------------------- /fr/section_4/README.md: -------------------------------------------------------------------------------- 1 | # Section 4 2 | -------------------------------------------------------------------------------- /fr/section_4/array-functions.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Array Functions 4 | --- 5 | 6 | # Array Functions 7 | 8 | ## `repeat` 9 | 10 | Syntax 11 | 12 | ```go 13 | array.repeat(number type) 14 | ``` 15 | 16 | Makes an array with the given element number of times. 17 | 18 | ```go 19 | foo := [1, 2].repeat(5) 20 | println(foo) // [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] 21 | ``` 22 | 23 | ## `delete` 24 | 25 | Syntax 26 | 27 | ```go 28 | array.delete(ix type) 29 | ``` 30 | 31 | Deletes the element present in the array at index `ix`. 32 | 33 | ```go 34 | mut even_numbers := [2, 4, 6, 8, 10] 35 | even_numbers.delete(3) 36 | println(even_numbers) // [2, 4, 6, 10] 37 | ``` 38 | 39 | ## `reverse` 40 | 41 | Syntax 42 | 43 | ```go 44 | array.reverse() 45 | ``` 46 | 47 | Reverses the array. 48 | 49 | ```go 50 | float_num := [1.1, 1.3, 1.25, 1.4] 51 | float_num.reverse() // [1.4, 1.25, 1.3, 1.1] 52 | ``` 53 | 54 | ## `clone` 55 | 56 | Syntax 57 | 58 | ```go 59 | array.clone() 60 | ``` 61 | 62 | Clones and returns a new array. 63 | 64 | ```go 65 | foo := [1, 2, 4, 5, 4, 6] 66 | foo1 := foo.clone() 67 | println(foo1) // [1, 2, 4, 5, 4, 6] 68 | ``` 69 | -------------------------------------------------------------------------------- /fr/section_4/files.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Files 4 | --- 5 | 6 | # Files 7 | 8 | A File in V is an abstraction of any file object accessible by the program and is closely associated with `os` library. 9 | 10 | ## Reading Files 11 | 12 | Reading a file is an important task to tackle several different problems in computer science. In order to accomplish this task you can use the V native library `os` as described below: 13 | 14 | ```go 15 | import os 16 | 17 | fn main() { 18 | mut fp := flag.new_flag_parser(os.args) 19 | generator := fp.string('generator', '', 'generator name') 20 | method := fp.string('method', '', 'generator method name') 21 | path := './data/$generator/$method' 22 | 23 | if os.file_exists(path) { 24 | print_generator_sample(path) 25 | } else { 26 | println('File does not exist') 27 | return 28 | } 29 | } 30 | 31 | fn print_generator_sample(path string) { 32 | contents := os.read_file(path.trim_space()) or { 33 | println('Failed to open $path') 34 | return 35 | } 36 | 37 | lines := contents.split_into_lines() 38 | length := lines.len 39 | 40 | print_random_element(lines, length) 41 | } 42 | 43 | fn print_random_element(lines []string, length int) { 44 | rand.seed(time.now().uni) 45 | 46 | println(lines[rand.next(length-1)]) 47 | } 48 | ``` 49 | 50 | ## Writing files 51 | 52 | Writing files in V is similar to read files. 53 | 54 | ```go 55 | import os 56 | 57 | fn main() { 58 | path := './data/file.txt' 59 | text := 'Full text description.' 60 | 61 | if contents := os.write_file(path, text) or { 62 | println('Failed while creating file') 63 | return 64 | } 65 | 66 | content_lines = read_file(path) 67 | print(content_lines) 68 | } 69 | 70 | fn read_file(path string) { 71 | contents := os.read_file(path.trim_space()) or { 72 | println('Failed to open $path') 73 | return 74 | } 75 | 76 | return contents.split_into_lines() 77 | } 78 | ``` 79 | 80 | ## Exercises 81 | 82 | 1. Write a V program to create a new file with content. 83 | 2. Write a V program to read 2 different files and display their content. 84 | 3. Read how the `os` library works in V and understand how you could use it. 85 | 4. Encode a nested json string and write a new file with the result. 86 | -------------------------------------------------------------------------------- /fr/section_4/json.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: JSON 4 | --- 5 | 6 | # JSON 7 | 8 | JavaScript Object Notation (JSON) is a lightweight data-interchange format that is easy for humans to read and write. Furthermore, equally simple for machines to generate and/or parse. 9 | JSON is completely language agnostic and that's why it's the ideal interchange format. 10 | 11 | To read more about JSON visit: [json.org](http://json.org). 12 | 13 | ## Parsing JSON 14 | 15 | To parse a JSON string received by another application or generated within your existing application: 16 | 17 | ```go 18 | import json 19 | 20 | struct Customer { 21 | first_name string 22 | last_name string 23 | hometown string 24 | } 25 | 26 | fn main() { 27 | customers_string := '[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro" }, { "first_name": "Don", "last_name": "Nisnoni", "hometown": "Kupang" }]' 28 | customers := json.decode([]Customer, customers_string) or { 29 | eprintln('Failed to parse json') 30 | return 31 | } 32 | 33 | // Print the list of customers 34 | for customer in customers { 35 | println('$customer.first_name $customer.last_name: $customer.hometown') 36 | } 37 | } 38 | ``` 39 | 40 | ## Generating JSON 41 | 42 | Creating a JSON string for communication or serialization is just as simple. We decode and encode in the example below: 43 | 44 | ```go 45 | import json 46 | 47 | struct Customer { 48 | first_name string 49 | last_name string 50 | hometown string 51 | } 52 | 53 | fn main() { 54 | customer_string := '[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro"}]' 55 | 56 | customer := json.decode([]Customer, customer_string) or { 57 | eprintln('Failed to parse json') 58 | return 59 | } 60 | 61 | encoded_json := json.encode(customer) 62 | 63 | println(encoded_json) 64 | } 65 | ``` 66 | 67 | ## Exercises 68 | 69 | 1. Compare how you handle JSON in your favorite language and V. 70 | 2. Build an `Address` struct that contains address information. 71 | 3. Use the `Address` struct to decode and encode a string that contains JSON format. 72 | 4. Create 2 structs: `Address` and `User` where a user has many addresses. Now receive a string with a nested JSON like `'[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro", "addresses": [{ street_name: "Rua Princesa Isabel", city: "Rio de Janeiro", country: "Brazil" }] }]'`, decode and encode it. 73 | -------------------------------------------------------------------------------- /fr/section_4/testing.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Testing 4 | --- 5 | 6 | # Testing 7 | 8 | Testing in software development is a process that aims to evaluate the functionality of an application with an intent to find whether the code met the specified requirements or not as well as identifying the problems to ensure that the product has expected quality. 9 | 10 | ## Automated tests 11 | 12 | Automated tests follow the process of testing the software using an automation tool to find the defects. In this process, programmers execute the test scripts and generate the test results automatically by using automation tools. 13 | 14 | ## Tests in V 15 | 16 | In V, all test files have to be named with the following format: `*_test.v` and the functions should start with `test_*`. 17 | 18 | ```go 19 | // sum.v in subfolder sum 20 | module sum 21 | 22 | pub fn sum(a, b int) int { 23 | return a + b 24 | } 25 | ``` 26 | 27 | ```go 28 | // sum_test.v 29 | import sum 30 | 31 | fn test_sum() { 32 | assert sum.sum(2, 3) == 5 33 | // assert sum.sum(2, 3) == 777 // => sum_test.v:6: FAILED assertion 34 | } 35 | ``` 36 | 37 | To execute the test, you should run `v test_sum.v`. 38 | 39 | ### Examples 40 | 41 | 1. Testing JSON structures: 42 | 43 | ```go 44 | import json 45 | 46 | fn test_encode_customer(){ 47 | customer := Customer{ first_name: "Vitor", last_name: "Oliveira" } 48 | expected := '{ "first_name": "Vitor", "last_name": "Oliveira" }' 49 | 50 | encoded_json := json.encode(customer) 51 | assert encoded_json == expected 52 | } 53 | ``` 54 | 55 | 2. Testing files: 56 | 57 | ```go 58 | import os 59 | 60 | fn test_file_creation() { 61 | file_name := './new_file.txt' 62 | content := 'text' 63 | 64 | os.write_file(file_name, content) 65 | assert content.len == os.file_size(file_name) 66 | 67 | os.rm(file_name) 68 | } 69 | ``` 70 | -------------------------------------------------------------------------------- /id/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ## General 4 | 5 | Please ensure your pull request adheres to the following guidelines: 6 | 7 | * New example or improvements to existing examples are welcome. 8 | * Please check your spelling and grammar. 9 | 10 | ## Adding a New Example 11 | 12 | To add a new example, create a new folder and a file or a file (depending upon the example) under the appropriate directory in `./examples`. Please check the `.plan` file to see what examples we plan to create. Feel free to work on any pending examples. We're happy to read/review your changes and collaborate/code with you to merge them. 13 | 14 | Thank you for your contributions! 15 | 16 | ## Getting started with the project 17 | 18 | ### 1. Fork and clone this repository 19 | 20 | [Fork this repository](https://github.com/v-community/v_by_example/fork) and clone your fork. If you don't know what forking means or don't know how to do it, nice instructions are available [here](https://help.github.com/articles/fork-a-repo/). 21 | 22 | #### 2. Make your changes and push them 23 | 24 | Now you're ready to make your changes! Once you're done with your changes, push those changes to your fork and then [submit a **pull request**](https://help.github.com/articles/using-pull-requests/). 25 | 26 | ## License 27 | 28 | This code is free to use under the terms of the MIT license. 29 | -------------------------------------------------------------------------------- /id/README.md: -------------------------------------------------------------------------------- 1 | # V dengan Contoh 2 | 3 | [Brazilian Portuguese](/pt-br/README.md) | [Deutsch](/de/README.md) | [English](/en/README.md) | [Bahasa Indonesia](README.md) | [Chinese](/cn/README.md) 4 | 5 | > Belajar V dengan Contoh 6 | 7 | V by Example adalah pengantar langsung ke V dengan menggunakan contoh program beranotasi. 8 | 9 | * [Contoh-contoh](examples/README.md) 10 | * [Berkontribusi](#contributing) 11 | * [Lisensi](#license) 12 | 13 | Discord: [https://discord.gg/d3Qk65J](https://discord.gg/d3Qk65J) 14 | 15 | ## Bagian 1 16 | 17 | Pengenalan V dengan menghadirkan beberapa contoh dan latihan dasar. 18 | 19 | * [Hello World](examples/section_1/hello_world.md) 20 | * [V Keywords](examples/section_1/keywords.md) 21 | * [Primitives](examples/section_1/primitives.md) 22 | * [Variables](examples/section_1/variables.md) 23 | * [Strings](examples/section_1/strings.md) 24 | * [Comment](examples/section_1/comment.md) 25 | 26 | ## Bagian 2 27 | 28 | Bagian ini membahas tentang operator utama dan pernyataan bersyarat dalam V. 29 | 30 | * [Operator](examples/section_2/operator.md) 31 | * [If-else](examples/section_2/if-else.md) 32 | * [Match](examples/section_2/match.md) 33 | * [Loops](examples/section_2/loops.md) 34 | 35 | ## Bagian 3 36 | 37 | Bagian ini membahas tentang fungsi dan metode dan dalam struktur data yang paling penting dalam V: array dan struct. 38 | 39 | * [Functions](examples/section_3/functions.md) 40 | * [Arrays](examples/section_3/arrays.md) 41 | * [Struct](examples/section_3/struct.md) 42 | * [Methods](examples/section_3/methods.md) 43 | 44 | ## Bagian 4 45 | 46 | Di bagian ini, kita akan membahas lebih dalam dan mempelajari fitur-fitur di dalam objek Array. Contoh-contoh lain seperti JSON, Menulis / membaca file dan Testing juga akan dibahas. 47 | 48 | * [Array Functions](examples/section_4/array-functions.md) 49 | * [Testing](examples/section_4/testing.md) 50 | * [Files](examples/section_4/files.md) 51 | * [JSON](examples/section_4/json.md) 52 | 53 | ## Tim 54 | 55 | Daftar pengelola/penulis saat ini: 56 | 57 | * [Don Alfons Nisnoni](https://github.com/donnisnoni95) 58 | * [Ivo-Balbaert](https://github.com/ibalbaert) 59 | * [Sven Patrick Meier](https://github.com/SuicideS3ason) 60 | * [Swastik Baranwal](https://github.com/Delta456) 61 | * [Vitor Oliveira](https://github.com/vbrazo) 62 | 63 | ## Berkontribusi 64 | 65 | Lihat [CONTRIBUTING.md](CONTRIBUTING.md) kami dan mulai berkontribusi hari ini. Kami biasanya memilih pengelola baru berdasarkan kontribusi 66 | 67 | ## Lisensi 68 | 69 | [MIT](/LICENSE) 70 | -------------------------------------------------------------------------------- /id/examples/README.md: -------------------------------------------------------------------------------- 1 | # Contoh-contoh 2 | -------------------------------------------------------------------------------- /id/examples/section1/README.md: -------------------------------------------------------------------------------- 1 | # Bagian 1 2 | 3 | - [Variabel](variables.md) 4 | -------------------------------------------------------------------------------- /id/examples/section1/variables.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Variabel 4 | --- 5 | 6 | # Variabel 7 | 8 | Variabel pada V dapat dinyatakan dan diinisialisasi dengan `:=` operator. Variabel hanya dapat dideklarasikan dengan cara ini dalam V, ini berarti semua variabel memiliki nilai awal. Jenis variabel disimpulkan dari nilai di sisi kanan. Secara _default_ variabel dalam V tidak dapat diubah(_immutable_). 9 | 10 | ```go 11 | umur := 23 // int 12 | nama := 'Alice' // string 13 | sudah_dewasa := age > 21 // bool 14 | 15 | println(umur) // 23 16 | println(nama) // Alice 17 | println(sudah_dewasa) // true 18 | ``` 19 | 20 | > Catatan: Variabel hanya dapat didefinisikan di dalam suatu fungsi. Tidak ada variabel global dan tidak ada variabel global di V. 21 | 22 | Untuk mengubah nilai variabel, kita harus membuatnya _mutable_. Ini dapat dilakukan dengan menggunakan _keyword_ `mut` ketika mendeklarasikan variabel. Untuk menetapkan nilai baru ke variabel, gunakan `=` 23 | 24 | ```go 25 | mut umur := 20 // mendeklarasikan umur variabel yang bisa berubah dan menetapkannya ke nilai 20. 26 | println(umur) // 20 27 | umur = 21 // tetapkan nilai baru ke variabel umur 28 | println(umur) // 21 29 | ``` 30 | 31 | Meninggalkan kata kunci `mut` di sini akan menghasilkan _error_ karena nilai variabel yang _immutable_ tidak dapat diubah. 32 | 33 | ```go 34 | fn main() { 35 | umur = 20 36 | println(umur) 37 | } 38 | ``` 39 | 40 | Kode di atas akan menghasilkan _error_ selama kompilasi karena variabel `umur` tidak dideklarasikan, 41 | 42 | ```go 43 | fn main() { 44 | mut umur := 20 // mendeklarasikan variabel yang immutable umur dan berikan nilai 20. 45 | println(umur) // 20 46 | umur := 21 // ERROR 47 | } 48 | ``` 49 | 50 | di sini `age: = 21` akan menghasilkan _error_ lain ketika dikompile karena variabel `umur` sudah didefinisikan dalam ruang lingkup. Sangat mudah diingat, cukup nyatakan nilai dengan `:=` dan tetapkan nilai dengan `=`. 51 | 52 | Seperti Go, Kamu juga dapat menggunakan `_` untuk mengabaikan nilai saat tidak diperlukan. Biasanya digunakan dalam fungsi _multi return_. 53 | 54 | ```go 55 | _ := "Saya tidak membutuhkan nilai ini" 56 | println(_) // ERROR: Cannot use `_` as value 57 | ``` 58 | 59 | ## Aturan Penamaan 60 | 61 | Berikut ini adalah aturan-aturan yang harus diingat saat menamai variabel. 62 | 63 | - Nama tidak boleh mengandung huruf besar seperti `AlphaTest` 64 | - Gunakan garis bawah sebagai pemisah seperti `hello_world` 65 | - Nama harus sejelas mungkin 66 | - Nama tidak boleh mengandung `__` 67 | - Nama tidak boleh mengandung spasi apa pun 68 | - Jika nama lebih panjang dari 11 maka harus menggunakan `_` sebagai pemisah 69 | 70 | Aturan-aturan ini berasal dari [`Snake_Case`](https://en.wikipedia.org/wiki/Snake_case). V menggunakan Snake Case dan memilihnya karena lebih mudah dibaca, ditulis, dan dimengerti. 71 | 72 | ### Nama yang Valid 73 | 74 | ```go 75 | boby 76 | ayah_jhon 77 | nomor_keluargaku 78 | ``` 79 | 80 | ### Nama yang tidak Valid 81 | 82 | ```go 83 | SayaTidakValid 84 | new Buat 85 | ``` 86 | -------------------------------------------------------------------------------- /it/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ## General 4 | 5 | Please ensure your pull request adheres to the following guidelines: 6 | 7 | * New example or improvements to existing examples are welcome. 8 | * Please check your spelling and grammar. 9 | 10 | ## Adding a New Example 11 | 12 | To add a new example, create a new folder and a file or a file (depending upon the example) under the appropriate directory in `./examples`. Please check the `.plan` file to see what examples we plan to create. Feel free to work on any pending examples. We're happy to read/review your changes and collaborate/code with you to merge them. 13 | 14 | Thank you for your contributions! 15 | 16 | ## Getting started with the project 17 | 18 | ### 1. Fork and clone this repository 19 | 20 | [Fork this repository](https://github.com/v-community/v_by_example/fork) and clone your fork. If you don't know what forking means or don't know how to do it, nice instructions are available [here](https://help.github.com/articles/fork-a-repo/). 21 | 22 | #### 2. Make your changes and push them 23 | 24 | Now you're ready to make your changes! Once you're done with your changes, push those changes to your fork and then [submit a **pull request**](https://help.github.com/articles/using-pull-requests/). 25 | 26 | ## License 27 | 28 | This code is free to use under the terms of the MIT license. 29 | -------------------------------------------------------------------------------- /it/README.md: -------------------------------------------------------------------------------- 1 | # V per Esempi 2 | 3 | [Brasiliano Portughese](/pt-br/README.md) | [Tedesco](/de/README.md) | [Inglese](/en/README.md) | [Bahasa Indonesia](/id/README.md) | [Cinese](/cn/README.md) | [Giapponese](jp/README.md) | [Italian](README.md) 4 | 5 | > Impara V per Esempi 6 | 7 | V per Esempi è un'introduzione diretta a V, utilizzando programmi di esempio con annotazioni 8 | 9 | * [Esempi](examples/README.md) 10 | * [Contributi](#contributing) 11 | * [Licenze](#license) 12 | 13 | Discord: [https://discord.gg/vlang](https://discord.gg/vlang) 14 | 15 | ## Capitolo 1 16 | 17 | Una introduzione a V per presentare un po' esempi base ed esercizi. 18 | 19 | * [Hello World](examples/section_1/hello_world.md) 20 | * [V Parole riservate](examples/section_1/keywords.md) 21 | * [Primitive](examples/section_1/primitives.md) 22 | * [Variabili](examples/section_1/variables.md) 23 | * [Stringhe](examples/section_1/strings.md) 24 | * [Commento](examples/section_1/comment.md) 25 | 26 | ## Capitolo 2 27 | 28 | Questa sezione riguarda i principali operatori e le dichiarazioni condizionali in V. 29 | 30 | * [Operatore](examples/section_2/operator.md) 31 | * [If-else](examples/section_2/if-else.md) 32 | * [Match](examples/section_2/match.md) 33 | * [Cicli](examples/section_2/loops.md) 34 | 35 | ## Capitolo 3 36 | 37 | Uno studio sulle funzioni, metodi e sulle più importanti strutture dati in V: array e struct. 38 | 39 | * [Funzioni](examples/section_3/functions.md) 40 | * [Arrays](examples/section_3/arrays.md) 41 | * [Struct](examples/section_3/struct.md) 42 | * [Metodi](examples/section_3/methods.md) 43 | 44 | ## Capitolo 4 45 | 46 | In questa sezione, approfondiamo e studiamo le funzionalità degli oggetti di tipo Array. Inoltre sono trattati altri esempi come JSON, Scrittura/lettura di file e fare test. 47 | 48 | * [Array di Funzioni](examples/section_4/array-functions.md) 49 | * [Fare Test](examples/section_4/testing.md) 50 | * [File](examples/section_4/files.md) 51 | * [JSON](examples/section_4/json.md) 52 | 53 | ## Team 54 | 55 | Lista attuale dei manutentori/autori: 56 | 57 | * [Don Alfons Nisnoni](https://github.com/dhonx) 58 | * [Ivo-Balbaert](https://github.com/ibalbaert) 59 | * [Sven Patrick Meier](https://github.com/SuicideS3ason) 60 | * [Swastik Baranwal](https://github.com/Delta456) 61 | * [Vitor Oliveira](https://github.com/vbrazo) 62 | 63 | ## Contributi 64 | 65 | Guarda i nostri contributi [CONTRIBUTING.md](CONTRIBUTING.md) e inizia da oggi a contribuire anche tu. Solitamente eleggiamo nuovi manutentori in base ai contributi. 66 | 67 | ## Licenza 68 | 69 | [MIT](/LICENSE) 70 | -------------------------------------------------------------------------------- /it/examples/README.md: -------------------------------------------------------------------------------- 1 | # Esempi 2 | -------------------------------------------------------------------------------- /it/examples/section_1/README.md: -------------------------------------------------------------------------------- 1 | # Section 1 2 | -------------------------------------------------------------------------------- /it/examples/section_1/comment.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Commenti 4 | --- 5 | 6 | # Commenti 7 | 8 | V supporta i commenti su una sola riga `//` e i commenti su più righe `/* */`. 9 | Dovrebbero essere usati per documentare il codice per far capire agli altri utenti come funziona il codice. 10 | Può anche essere utilizzato per commentare temporaneamente il codice che dovrà essere usato in seguito. 11 | 12 | ```v 13 | // Questo è un commento su una sola riga 14 | 15 | /* Queto è un 16 | * commento su più righe 17 | * /* Questo può essere a sua volta annidato*/ 18 | */ 19 | ``` 20 | -------------------------------------------------------------------------------- /it/examples/section_1/hello_world.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Stampa formattata 4 | --- 5 | 6 | # Stampa formattata 7 | 8 | La stampa è gestita da varie funzioni di stream I/O. Di conseguenza bisognerebbe sapere dove usarle. 9 | 10 | - `print`: per stampare il testo nello stream di output senza un a capo. 11 | 12 | - `println`: come `print`, ma aggiunge automaticamente un a capo. 13 | 14 | - `eprint`: come `print`, ma l'output finisce nello stream di errore (stderr). 15 | 16 | - `eprintln`: come `println`, ma l'output finisce nello stream di errore (stderr). 17 | 18 | - `panic`: restituisce l'output ed esce dal programma. 19 | 20 | ```v 21 | print('Hello World') 22 | print('Hello V') 23 | ``` 24 | 25 | Questo stamperà `Hello WorldHello V` 26 | 27 | Se vuoi stampare la riga successiva, scrivendo su una nuova linea, dovresti utilizzare `\n`. 28 | 29 | ```v 30 | print('Hello World \n') 31 | print('Hello V ') 32 | ``` 33 | 34 | Se non vuoi usare `\n` allora, al suo posto, puoi usare `println`. 35 | 36 | ## Esercizi 37 | 38 | Prova a togliere i commenti nel file `hello.v` e vedi cosa succede. 39 | -------------------------------------------------------------------------------- /it/examples/section_1/keywords.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Schlüsselwörter 4 | --- 5 | 6 | # Parole riservate 7 | 8 | V è un linguaggio piccolo, con poche parole riservate. Ci sono circa 25 parole riservate. 9 | 10 | | Parole riservate | nel | linguaggio di | Programmazione | V | 11 | | --------------- | ------ | ------------------ | -------------- | --------- | 12 | | break | const | as | continue | defer | 13 | | else | enum | fn | for | struct | 14 | | go | goto | if | import | return | 15 | | type | pub | mut | in | interface | 16 | | match | module | or | none | | 17 | 18 | Come in altri linguaggi, queste parole riservate non possono essere usate come nomi di una variabile. 19 | -------------------------------------------------------------------------------- /it/examples/section_1/primitives.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Datentypen 4 | --- 5 | 6 | # Dati primitivi 7 | 8 | V ha meno tipi di dati primitivi di Go. 9 | 10 | ## Tipi base 11 | 12 | - bool ovvero `true` oppure `false` 13 | 14 | - striga 15 | 16 | - tipo intero `int` 17 | 18 | - tipo float `float` 19 | 20 | - rune (stinga Unicode) 21 | 22 | ## Tipi composti 23 | 24 | - vettori `[]`. 25 | 26 | - mappe `{}` 27 | 28 | - strutture. 29 | 30 | ## Intero 31 | 32 | L'intero è a sua volta classificato in `signed` e `unsigned`. `signed` significa positivo o negativo e `unsigned` significa solo positivo. 33 | 34 | ### Intero con segno 35 | 36 | | Tipo | Dimensione | Intervallo | 37 | | ------ | :---------: | -------------------------------------: | 38 | | int8 | 8 bits | -128 a 27 -1 | 39 | | int16 | 16 bits | -215 a 215 - 1 | 40 | | int | 32 bits | -231 a 231 - 1 | 41 | | int64 | 64 bits | -263 a 263 - 1 | 42 | | int128 | 128 bits | -2127 a 2127 - 1 | 43 | 44 | ### Intero senza segno 45 | 46 | | Tipo | Dimensione | Intervallo | 47 | | ---- | :--------: | ------------------------: | 48 | | byte | 8 bits | 0 bis 27 -1 | 49 | | u16 | 16 bits | 0 bis 215 - 1 | 50 | | u32 | 32 bits | 0 bis 231 - 1 | 51 | | u64 | 64 bits | 0 bis 263 - 1 | 52 | | u128 | 128 bits | 0 bis 2127 - 1 | 53 | -------------------------------------------------------------------------------- /it/examples/section_1/variables.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Variables 4 | --- 5 | 6 | # Variabili 7 | 8 | In V le variabili possono essere dichiarate e inizializzate con l'operatore `:=`. Le variabili possono essere dichiarate solo il in questo modo in V, questo significa che tutte le variabili hanno un valore iniziale. Il tipo di una variabile è dedotto dal valore alla sua destra. Di default le variabili in V sono immutabili. 9 | 10 | ```go 11 | age := 23 // int 12 | name := 'Alice' // string 13 | is_adult := age > 21 // bool 14 | 15 | println(age_str) // 23 16 | println(name) // Alice 17 | println(is_adult) // true 18 | ``` 19 | 20 | > Nota: Le variabili possono solo essere definite in una funzione. Non ci sono variabili globali o stati globali in V. 21 | 22 | Per cambiare il valore di una variabile, bisogna renderla mutabile. Questo può essere fatto usando la parola riservata `mut` quando dichiariamo la variabile. Per assegnare un nuovo valore alla variabile si usa `=`. 23 | 24 | ```go 25 | mut age := 20 // dichiaro mutabile la variabile age e le assegno il valore 20. 26 | println(age) // 20 27 | age = 21 // assegno un nuovo valore a age 28 | println(age) // 21 29 | ``` 30 | 31 | Senza la parola ridervata `mut` ci darà un errore perché il valore di una variabile immutabile non può essere cambiato. 32 | 33 | ```go 34 | fn main() { 35 | age = 20 36 | println(age) 37 | } 38 | ``` 39 | 40 | Il codice sopra darà un errore durante la compilazione perché la varaibile `age` non è dichiarata, 41 | 42 | ```go 43 | fn main() { 44 | mut age := 20 // dichiariamo mutabile la variabile age e le assegnamo il valore 20. 45 | println(age) // 20 46 | age := 21 // ERROR 47 | } 48 | ``` 49 | 50 | in questo caso `age := 21` darà un altro errore durante la compilazione perché la varaibile `age` è gia definita nello scope. E' molto semplice da ricordare, per dichiarare un valore `:=` e per assegnare un valore `=`. 51 | 52 | Come in Go, puoi anche usare `_` per ignorare il valori quando non sono necessari. Di solito si usa nelle funzioni che ritornano più valori. 53 | 54 | ```go 55 | _ := "I don't need this value" 56 | println(_) // ERROR: Cannot use `_` as value 57 | ``` 58 | 59 | ## Regole per i nomi 60 | 61 | Le seguenti solo le regole che dovrebbero essere tenute a mente quando si danno i nomi alle variabili. 62 | 63 | - Il nome non dovrebbe contenere leettere Maiuscole come `AlphaTest` 64 | - Usa i trattini bassi come separatore, ad esempio `hello_world` 65 | - Il nome dovrebbe essere il più possibile descrittivo 66 | - Il nome non dovrebbe contenere `__` 67 | - Il nome non dovrebbe contenere spazi 68 | - Se il nome è più lungo di 11 caratteri allora devi usare `_` come separatore 69 | 70 | Queste regole provengono da [`Snake_Case`](https://en.wikipedia.org/wiki/Snake_case). V utilizza lo Snake Case e si preferisce perché è molto più facile da leggere, scrivere e capire. 71 | 72 | ### Nomi validi 73 | 74 | ```go 75 | boby 76 | john_dads 77 | myfamily_number 78 | ``` 79 | 80 | ### Nomi non validi 81 | 82 | ```go 83 | IamNotValid 84 | new Make 85 | ``` 86 | -------------------------------------------------------------------------------- /jp/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # 貢献方法 2 | 3 | ## 概要 4 | 5 | プルリクエストを送る場合、以下のガイドラインを満たしているか確認してください。 6 | 7 | * 新しいコード例の追加や既存コード例の改善は歓迎されます。 8 | * スペルや文法を確認してください。 9 | 10 | ## コード例のバージョンに関する注意事項 11 | 12 | 全てのコード例には、下記のようなヘッダーを含める必要があります。 13 | 14 | ```markdown 15 | --- 16 | version: 3.5.1 17 | example_title: JSON操作 18 | --- 19 | ``` 20 | 21 | 次のルールに従い `version` 属性の変更を行います。 22 | 23 | * メジャー :コンテンツ全体の作成(もしくは作成し直し)。新しいコンテンツには翻訳が必要です。 24 | * マイナー:一部のコンテンツや文章などの追加、削除。 25 | * パッチ: スペルミスやタイプミス。おそらく翻訳を必要としないもの。 26 | 27 | [SemVer.org](https://semver.org) のパターンにしたがいます。 これは、翻訳を必要とする新しいコンテンツを決定し、翻訳者に知らせる際に使用するため重要となります。 28 | 29 | ## 新しいコード例の追加 30 | 31 | 新しいコード例を追加するには、`./examples` の適切なディレクトリの配下に、新しいフォルダとファイル、もしくはコード例に応じたファイルを作成します。どのようなコード例を作成する予定かは、`.plan` ファイルを確認してください。保留されているコード例があれば、自由に作業を行ってください。あなたが変更した箇所を読んでレビューをしたり、共にコーディングを行いマージされるのを楽しみにしています。 32 | 33 | ご協力に感謝いたします! 34 | 35 | ## スタートガイド 36 | 37 | ### 1. リポジトリをフォークしクローンする 38 | 39 | [このリポジトリ](https://github.com/v-community/v_by_example/fork) をフォークし、フォークからクローンを作成します。フォークが何なのか、どのように使うのか分からない方は、[こちら](https://help.github.com/articles/fork-a-repo/)がとても参考になります。 40 | 41 | ### 2.作業を行いプッシュする 42 | 43 | 作業を行う準備は整いました。作業が完了したら、変更内容を自身のフォークにプッシュし[プルリクエスト](https://help.github.com/articles/using-pull-requests/)を送りましょう。 44 | 45 | ## ライセンス 46 | 47 | このコードは、MITライセンスの下で自由に使用できます。 48 | -------------------------------------------------------------------------------- /jp/README.md: -------------------------------------------------------------------------------- 1 | # コード例で学ぶV言語 2 | 3 | [Brazilian Portuguese](pt-br/README.md) | [Deutsch](de/README.md) | [English](en/README.md) | [Bahasa Indonesia](id/README.md) | [Chinese](cn/README.md) | [Japanese](jp/README.md) 4 | > コード例で学ぶV言語 5 | 6 | 「コード例で学ぶV言語」は、各種プログラム例を用いてV言語(以下大文字のV)をストレートに紹介します。 7 | 8 | - [コード例](#examples) 9 | - [貢献方法](#contributing) 10 | - [ライセンス](#license) 11 | 12 | Discord: [https://discord.gg/d3Qk65J](https://discord.gg/d3Qk65J) 13 | 14 | ## セクション1 15 | 16 | いくつかの基本コード例や演習をこなしながらVを紹介します。 17 | 18 | - [Hello World](examples/section_1/hello_world.md) 19 | - [Vのキーワード](examples/section_1/keywords.md) 20 | - [プリミティブ型](examples/section_1/primitives.md) 21 | - [変数](examples/section_1/variables.md) 22 | - [文字列](examples/section_1/strings.md) 23 | - [コメント](examples/section_1/comment.md) 24 | 25 | ## セクション2 26 | 27 | Vにおける主要な演算子や条件文について説明します。 28 | 29 | - [演算子](examples/section_2/operator.md) 30 | - [If-else文](examples/section_2/if-else.md) 31 | - [マッチ](examples/section_2/match.md) 32 | - [ループ](examples/section_2/loops.md) 33 | 34 | ## セクション3 35 | 36 | 関数(function)やメソッド(method)、そしてVにおける最も重要なデータ構造である配列(array)や構造体(struct)について学びます。 37 | 38 | - [関数](examples/section_3/functions.md) 39 | - [配列](examples/section_3/arrays.md) 40 | - [構造体](examples/section_3/struct.md) 41 | - [メソッド](examples/section_3/methods.md) 42 | 43 | ## セクション4 44 | 45 | このセクションでは、Arrayオブジェクトの内部機能を詳しく学びます。他にJSON、ファイル入出力、テストの書き方についても扱います。 46 | 47 | - [配列の関数](examples/section_4/array-functions.md) 48 | - [テストの書き方](examples/section_4/testing.md) 49 | - [ファイル操作](examples/section_4/files.md) 50 | - [JSON操作](examples/section_4/json.md) 51 | 52 | ## チーム 53 | 54 | 現時点のメンテナー/著者のリストは以下のとおりです。 55 | 56 | - [Don Alfons Nisnoni](https://github.com/dhonx) 57 | - [Ivo-Balbaert](https://github.com/ibalbaert) 58 | - [Sven Patrick Meier](https://github.com/SuicideS3ason) 59 | - [Swastik Baranwal](https://github.com/Delta456) 60 | - [Vitor Oliveira](https://github.com/vbrazo) 61 | 62 | ## 貢献方法 63 | 64 | [CONTRIBUTING.md](CONTRIBUTING.md)を読んで、早速コントリビューションを始めましょう。私たちは新しいメンテナーを主に貢献度で選んでいます。 65 | 66 | ## ライセンス 67 | 68 | [MIT](LICENSE) 69 | -------------------------------------------------------------------------------- /jp/code/hello_world/hello.v: -------------------------------------------------------------------------------- 1 | // Single line comments 2 | 3 | /* これは複数行コメントです。 4 | * /* このようにネストもできます。 */ 5 | * 6 | */ 7 | 8 | print('Hello V\n') 9 | print('Hello World') 10 | 11 | // 以下は出力後に自動改行します。 12 | // println('Hello V by Example') 13 | // eprintln('Hello V by Example') 14 | 15 | /*println('I am Bob and I am $age old') */ // これは出力されません(`$age`が未定義のため)。 16 | /* println(foo) */ // これも動きません(カスタムのstring関数が未定義のため) 17 | 18 | //panic('Exiting from the program') 19 | -------------------------------------------------------------------------------- /jp/examples/section_1/README.md: -------------------------------------------------------------------------------- 1 | # セクション1 2 | 3 | いくつかの基本コード例や演習をこなしながらVを紹介します。 4 | 5 | - [Hello World](hello_world.md) 6 | - [Vのキーワード](keywords.md) 7 | - [プリミティブ型](primitives.md) 8 | - [変数](variables.md) 9 | - [文字列](strings.md) 10 | - [コメント](comment.md) 11 | -------------------------------------------------------------------------------- /jp/examples/section_1/comment.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: コメント 4 | --- 5 | 6 | # コメント 7 | 8 | Vでは単一行コメント`//`と複数行コメント`/* */`をサポートしています。 9 | これらのコメントは、コードのしくみを他のユーザーに理解してもらうためのドキュメントに利用すべきです。 10 | 後で利用するコードを一時的にコメントアウトするのにも利用できます。 11 | 12 | ```v 13 | // 単一行コメント 14 | 15 | /* ここは 16 | * 複数行コメント 17 | * /* このようにネストしてもよい*/ 18 | */ 19 | ``` 20 | -------------------------------------------------------------------------------- /jp/examples/section_1/hello_world.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: hello world 4 | --- 5 | 6 | # 書式付き出力(formatted print) 7 | 8 | printによる出力は、さまざまなI/Oストリーム関数で用いられます。以下の違いについて知っておく必要があります。 9 | 10 | - `print`: テキストを出力ストリームに出力します(出力後は改行しません) 11 | 12 | - `println`: `print`と同じですが、出力後、自動的に改行される点が異なります。 13 | 14 | - `eprint`: `print`と同じですが、出力先はエラー用ストリーム(stderr)です。 15 | 16 | - `eprintln`: `println`と同じですが、出力先はエラー用ストリーム(stderr)です。 17 | 18 | - `panic`: 出力後、プログラムを終了します。 19 | 20 | ```v 21 | print('Hello World') 22 | print('Hello V') 23 | ``` 24 | 25 | 上は`Hello WorldHello V`を出力します。 26 | 27 | 1行目の出力後に次の行を改行したい場合は、`\n`を使います。 28 | 29 | ```v 30 | print('Hello World \n') 31 | print('Hello V ') 32 | ``` 33 | 34 | `\n`を書きたくないのであれば、`println`を使いましょう。 35 | 36 | ## コメント 37 | 38 | Vでは単一行コメント`//`と複数行コメント`/* */`を両方サポートしています。 39 | コメントは、コードの動作を他のユーザーに知らせるドキュメントを書くために用いるべきです。後で有効にしなければならないコードを一時的にコメントアウトするのにも使えます。 40 | 41 | ```v 42 | // This is a single line comment 43 | 44 | /* This is a 45 | * multi-line comment 46 | * /* This could be nested as well*/ 47 | */ 48 | ``` 49 | 50 | ## 演習 51 | 52 | `hello.v`のコードにあるコメントを解除して、何が起きるかを観察しましょう。 53 | -------------------------------------------------------------------------------- /jp/examples/section_1/keywords.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: キーワード 4 | --- 5 | 6 | # キーワード 7 | 8 | Vはきわめて小規模な言語なのでキーワードもごくわずか(25個程度)しかありません。 9 | 10 | | V | 言語 | に | 含まれる | キーワード | 11 | | -------- | ------ | --- | ----------- | --------- | 12 | | break | const | as | continue | defer | 13 | | else | enum | fn | for | struct | 14 | | go | goto | if | import | return | 15 | | type | pub | mut | in | interface | 16 | | match | module | or | none | | 17 | 18 | 他の言語と同様、これらのキーワードは変数名には使えません。 19 | -------------------------------------------------------------------------------- /jp/examples/section_1/primitives.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: プリミティブ型 4 | --- 5 | 6 | # プリミティブ型 7 | 8 | Vのプリミティブ型は、Go言語よりも少なくなっています。 9 | 10 | ## 基本型 11 | 12 | - bool型(`true`または`false`) 13 | 14 | - string型 15 | 16 | - integer型(`int`) 17 | 18 | - float型(`float`) 19 | 20 | - rune型(Unicodeコードポイント)-- `0xf09f9880`など 21 | 22 | ## 複合型 23 | 24 | - array型(`[]`) 25 | 26 | - map型(`{}`) 27 | 28 | - struct型 29 | 30 | ## integer型 31 | 32 | integer(整数)型はさらに`signed`(符号あり)と`unsigned`(符号なし)に分けられます。`signed`は正または負の値を表しますが、`unsigned`は正の値だけを表します。 33 | 34 | ### 符号あり整数 35 | 36 | | 型名 | サイズ | 値の範囲 | 37 | | -------- | :------: | --------------------------------------:| 38 | | `int8` | 8ビット | -128 〜 27 -1 | 39 | | `int16` | 16ビット | -215 〜 215 - 1 | 40 | | `int` | 32ビット | -231 〜 231 - 1 | 41 | | `int64` | 64ビット | -263 〜 263 - 1 | 42 | | `int128` | 128ビット | -2127 〜 2127 - 1 | 43 | 44 | ### 符号なし整数 45 | 46 | | 型名 | サイズ | 値の範囲 | 47 | | ------ | :------: | -----------------------: | 48 | | `byte` | 8ビット | 0 〜 27 -1 | 49 | | `u16` | 16ビット | 0 〜 215 - 1 | 50 | | `u32` | 32ビット | 0 〜 231 - 1 | 51 | | `u64` | 64ビット | 0 〜 263 - 1 | 52 | | `u128` | 128ビット | 0 〜 2127 - 1| 53 | -------------------------------------------------------------------------------- /jp/examples/section_1/strings.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: 文字列 4 | --- 5 | 6 | # 文字列 7 | 8 | Vでは文字列の定義も`:=`演算子で行えます。他の変数と同様、文字列もデフォルトでイミュータブルです。文字列を(リテラルとして)表現するときには`""`や`''`のどちらでも使えます。`vfmt`で書式を整えると、文字列リテラルを囲む`""`は、文字列の中に`'`を含んでいなければすべて`''`に変換されます。 9 | 10 | ```v 11 | name := 'Bob' 12 | println(name) // Bob 13 | println(name.len) // 3 14 | ``` 15 | 16 | 文字列の長さは`.len`で取得できます。 17 | 18 | ## 式展開(interpolation) 19 | 20 | 文字列の中で`$`に続けて変数名を書くと、変数の値を文字列に展開できます。 21 | 22 | ```v 23 | name:= 'Bob' 24 | println('Hello $name!') // Hello Bob! 25 | ``` 26 | 27 | 変数よりも複雑な式も、`${}`構文で式展開できます。 28 | 29 | ```v 30 | struct User { 31 | name string 32 | age int 33 | } 34 | bob := User { 35 | name: 'Bob' 36 | age: 17 37 | } 38 | println('Say Hello to a new User: ${bob.name}, ${bob.age}') 39 | // Say Hello to new User: Bob, 17 40 | println('${bob.name}s age is higher or equal to 18: ${bob.age >= 18}') 41 | // 0 <=> number representation for false 42 | ``` 43 | 44 | ## 文字列の結合 45 | 46 | 文字列は`+`演算子で結合できます。 47 | 48 | ```v 49 | text := 'Hello' 50 | concatenated_text := text + ' World!' 51 | println(text) // Hello 52 | println(text + ' World!') // Hello World! 53 | println(concatenated_text) // Hello World! 54 | ``` 55 | 56 | 文字列の後ろに別の文字列を結合する操作は`+=`演算子でも行えます。文字列はデフォルトでイミュータブルなので、この操作は`mut`と宣言されている場合にのみ可能です。 57 | 58 | ```v 59 | mut hello := 'Hello ' 60 | hello += 'from V!' // helloに保存されている文字列に'from V!'を追加する 61 | println(hello) // Hello from V! 62 | ``` 63 | 64 | Vの文字データはUTF-8でエンコードされます。また、文字データの実体はリードオンリーのバイト配列です。これによって文字列のスライシングが可能になります。つまり、単一文字のリテラルにアクセスすることも、文字列変数のスライスにアクセスすることもできます。 65 | 66 | ```v 67 | robert := 'Robert' 68 | bert := robert[2..robert.len] // bert 69 | rob := robert[0..3] // Rob 70 | println('The persons of interest are: $robert, $bert, $rob') // The persons of interest are: Robert, bert, Rob 71 | ``` 72 | 73 | ### 注意 74 | 75 | `some_string[開始位置..終了位置]`という構文の`終了位置`は、**終了位置そのものは含みません**(not inclusive)。 76 | 77 | Vのどの演算子についても、両辺に同じ型の値が必ず存在しなければなりません。以下のコードは、`age`が`int`型なのでコンパイルされません。 78 | 79 | ```v 80 | age := 25 81 | println('age = ' + age) // cannot convert `int` to `string` 82 | ``` 83 | 84 | つまり、`.str()`で文字列に変換するか、式展開を使う必要があります。Vでは式展開が推奨されています。 85 | 86 | ```v 87 | age := 25 88 | println('age = ' + age.str()) // age = 25 89 | println('age = $age') // age = 25 -- 推奨 90 | ``` 91 | 92 | 文字リテラルを定義するには` `` `を用います。raw stringの冒頭に`r`を付けるとエスケープされなくなります。 93 | 94 | ```v 95 | hello := 'Hello\nWorld' 96 | println(hello) // Hello 97 | // World 98 | raw_hello := r'Hello\nWorld' 99 | println(raw_hello) // Hello\nWorld 100 | ``` 101 | -------------------------------------------------------------------------------- /jp/examples/section_1/variables.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: 変数 4 | --- 5 | 6 | # 変数 7 | 8 | Vの変数は`:=`演算子で宣言および初期化できます。Vの変数はこれ以外の方法では宣言できません。つまり、いかなる変数にも初期値が存在するということです。変数の型は、右辺の値から推測されます。Vの変数はデフォルトでイミュータブル(immutable: 値を改変できない)です。 9 | 10 | ```v 11 | age := 23 // int 12 | name := 'Alice' // string 13 | is_adult := age > 21 // bool 14 | 15 | println(age_str) // 23 16 | println(name) // Alice 17 | println(is_adult) // true 18 | ``` 19 | 20 | > メモ: 変数の定義は、関数の内側でしか行なえません。Vにはグローバル変数もグローバルステートも存在しません。 21 | 22 | 変数の値を変更するには、変数がミュータブル(mutable: 改変可能)になっている必要があります。変数の宣言時に`mut`キーワードを用いることで、変数をミュータブルにできます。変数に新しい値を代入するには`=`を用います。 23 | 24 | ```v 25 | mut age := 20 // ミュータブルな変数ageを宣言して値20を代入する 26 | println(age) // 20 27 | age = 21 // ageに新しい値を代入する 28 | println(age) // 21 29 | ``` 30 | 31 | 上のコードは`mut`キーワードがないとエラーになります(イミュータブルな変数の値は変更できない)。 32 | v 33 | ```v 34 | fn main() { 35 | age = 20 36 | println(age) 37 | } 38 | ``` 39 | 40 | 上のコードはコンパイルの段階でエラーになります(変数`age`が宣言されていないため)。 41 | 42 | 43 | ```v 44 | fn main() { 45 | mut age := 20 // ミュータブルなage変数を宣言して値20を代入 46 | println(age) // 20 47 | age := 21 // ERROR 48 | } 49 | ``` 50 | 51 | 上の`age := 21`では、別のエラーがコンパイル時に発生します(変数`age`が同じスコープ内で既に定義されているため)。非常にシンプルで覚えやすいルールです。値の宣言は`:=`で、以後の代入は`=`と覚えておきましょう。 52 | 53 | Goと同様、不要な値は`_`で受け止めて無視できます。これは値を複数返す関数で使われるのが普通です【TBD】。 54 | 55 | ```v 56 | _, a := foo() 57 | println(_) // ERROR: Cannot use `_` as value 58 | ``` 59 | 60 | ## 命名のルール 61 | 62 | 以下は、変数の命名で守るべきルールの一覧です。 63 | 64 | - 大文字を含んではならない(✖`AlphaTest`) 65 | - 区切り文字にはアンダースコアを用いる(○`hello_world`) 66 | - できるかぎり、意味の明快な名前を付けること 67 | - 名前に`__`を含んではならない 68 | - 名前に(種類を問わず)スペース文字を含んではならない 69 | - 名前が11文字を超えたら必ず`_`で区切らなければならない 70 | 71 | 上のルールは[`snake_case`](https://en.wikipedia.org/wiki/Snake_case)が由来です。Vではsnake_caseスタイルが用いられ、また推奨されます(読みやすく、書きやすく、理解しやすいため)。 72 | 73 | ### 正しい名前 74 | 75 | ```v 76 | boby 77 | john_dads 78 | myfamily_number 79 | ``` 80 | 81 | ### 正しくない名前 82 | 83 | ```v 84 | IamNotValid 85 | new Make 86 | ``` 87 | -------------------------------------------------------------------------------- /jp/examples/section_2/README.md: -------------------------------------------------------------------------------- 1 | # セクション2 2 | 3 | Vにおける主要な演算子や条件文について説明します。 4 | 5 | - [演算子](operator.md) 6 | - [If-else文](if-else.md) 7 | - [マッチ](match.md) 8 | - [ループ](loops.md) 9 | -------------------------------------------------------------------------------- /jp/examples/section_2/if-else.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: if文 4 | --- 5 | 6 | # if文 7 | 8 | ## `if`文 9 | 10 | `if`文は、プログラミングにおける条件を記述する文であり、trueの場合は指定のブロック内のコードを実行します。以下はVにおける`if`文の一般的なコード例です。 11 | 12 | ```v 13 | john_height := 100 14 | maria_height := 178 15 | 16 | if john_height < maria_height { 17 | println("Maria is taller than John") 18 | } 19 | ``` 20 | 21 | 上のコードの`println()`は、条件がtrueの場合にのみ実行されます。 22 | 条件部分を丸かっこで囲む必要はありません。逆に波かっこ`{ }`は常に必要です。 23 | 24 | ## `else`文 25 | 26 | `else`文はプログラミングにおける条件を記述する文であり、`if`がfalseと評価された場合に`else`ブロックのコードを実行します。 27 | 28 | ```v 29 | joey_age := 12 30 | kevin_age := 15 31 | 32 | if joey_age > kevin_age { 33 | println("Joey is older") 34 | } else { 35 | println("Kevin is older") 36 | } 37 | ``` 38 | 39 | 上のコード例では、`else`ブロック内のコードが実行されます(`if`は`false`と評価されるため)。 40 | 41 | ## `else if`文 42 | 43 | `if...else`文は、評価式が`true`か`false`かに応じて異なるコードを実行します。しかし可能性のある選択肢が3つ以上になることもあります。`if...else if...else`のように重ねることで、複数の評価式をチェックして実行する文を切り替えることができます。 44 | 45 | ```v 46 | tom_age := 20 47 | ashia_age := 38 48 | 49 | if tom_age < ashia_age { 50 | println("Tom is younger than Ashia") 51 | } else if tom_age > ashia_age { 52 | println("Tom is older than Ashia") 53 | } else { 54 | println("Tom and Ashia are the same age") 55 | } 56 | ``` 57 | 58 | 上の出力結果: 59 | 60 | ```console 61 | Tom is younger than Asia 62 | ``` 63 | 64 | ## `if..else`文のネスト 65 | 66 | `if...else`文をネストすることで、別の`if`文や`else...if`文の中で`if`文や`else`文や`else...if`文を使えます。ネストは1回に留めるのがよい習慣です。 67 | 68 | ```v 69 | tom_age := 20 70 | ashia_age := 38 71 | 72 | if tom_age < ashia_age { 73 | if tom_age < 18 { 74 | println("tom_age < 18 and younger than Ashia.") 75 | } else { 76 | println("tom_age >= 18 and younger than Ashia.") 77 | } 78 | } else if tom_age > ashia_age { 79 | println("$tom_age > $ashia_age") 80 | } else { 81 | println("$tom_age == $ashia_age") 82 | } 83 | ``` 84 | 85 | 上の出力結果: 86 | 87 | ```console 88 | tom_age >= 18 and younger than Ashia. 89 | ``` 90 | 91 | ## `if..else`を式として扱う 92 | 93 | `if..else`は式としても扱えます。 94 | 95 | ```v 96 | tom_age := 20 97 | ashia_age := 38 98 | 99 | s := if tom_age < ashia_age { 100 | "Tom is the youngest" 101 | } else { 102 | "Ashia is the youngest" 103 | } 104 | 105 | print(s) 106 | ``` 107 | 108 | 上の出力結果: 109 | 110 | ```console 111 | Tom is the youngest 112 | ``` 113 | 114 | ## 演習 115 | 116 | 1. integerを2つ受け取り、両者が等しいかどうかをチェックするVプログラムを書きましょう。 117 | 2. 渡した数値が奇数か偶数かをチェックするVプログラムを書きましょう。 118 | 3. 渡した数値が正か負かをチェックするVプログラムを書きましょう。 119 | 4. 渡した年がうるう年かどうかをチェックするVプログラムを書きましょう。 120 | -------------------------------------------------------------------------------- /jp/examples/section_2/loops.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: ループを書く 4 | --- 5 | 6 | # ループを書く 7 | 8 | V言語のループ構文は1種類しかありません。Goでもこのループ構文は広く使われています。 9 | 10 | ## `for`ループ 11 | 12 | `for`ループは、何かを繰り返すための簡単かつ便利な方法を提供します。 13 | 値を変えながら同じコードを繰り返し実行するのも簡単です、 14 | ループについて考えるために、ゲームをコンピュータ化するときに人物をある方向にX歩進め、次に別の方向にY歩進める状況を考えてみましょう。 15 | たとえば「東に5歩進め」は以下のようにループで表現できます。 16 | 17 | ```v 18 | for i := 0; i < 5; i++ { 19 | println('Walking one step') 20 | } 21 | ``` 22 | 23 | Vの`for`ループは、さまざまな方法で構成できます。 24 | 25 | - arrayやmapで`in`演算子を使う 26 | 27 | ```v 28 | ages := [18, 25, 32, 43, 50] 29 | 30 | for age in ages { 31 | println(age) 32 | } 33 | ``` 34 | 35 | > 注意: 値はリードオンリーです。 36 | 37 | - `for`ループで条件を指定する 38 | 39 | これは、指定されたbool条件に応じてコードを繰り返し実行する制御フローを記述します。 40 | 条件部分を丸かっこで囲む必要はありませんが、波かっこ`{ }`は常に必要です。 41 | 42 | ```v 43 | mut factorial := 1 44 | mut counter := 1 45 | 46 | for { 47 | counter++ 48 | if counter > 5 { 49 | println(factorial) 50 | break 51 | } 52 | factorial = factorial * counter 53 | } 54 | 55 | println(counter) 56 | ``` 57 | 58 | 上の出力結果 59 | 60 | ```console 61 | 120 62 | 6 63 | ``` 64 | 65 | `break`文を使う`for`ループは、次のように`for`の直後の条件を反転させると、他の言語の`while`文と同等になってもっと短く書けます。 66 | 67 | ```v 68 | mut factorial := 1 69 | mut counter := 1 70 | 71 | for counter <= 5 { 72 | factorial = factorial * counter 73 | counter++ 74 | } 75 | println(factorial) 76 | println(counter) 77 | ``` 78 | 79 | Output 80 | 81 | ```console 82 | 120 83 | 6 84 | ``` 85 | 86 | - 伝統的なC言語風スタイル 87 | 88 | ```v 89 | mut factorial := 1 90 | mut counter := 1 91 | 92 | for counter = 1; counter < 6; counter++ { 93 | factorial = factorial * counter 94 | if counter == 5 { 95 | print(factorial) 96 | continue 97 | } 98 | println(counter) 99 | } 100 | ``` 101 | 102 | - 無限ループ 103 | 104 | `for`ループは無限回繰り返すこともできます。 105 | 106 | ```go 107 | for { 108 | println('foo') 109 | } 110 | ``` 111 | 112 | ## 演習 113 | 114 | 1. 自然数の最初の10個を表示するVプログラムを書きましょう。 115 | 2. 自然数の最初の10個の合計を求めるVプログラムを書きましょう。 116 | 3. arrayの中にあるintegerを表示し、それらの平均も表示するVプログラムを書きましょう。 117 | 4. キーボード入力から10個の数値を読み込み、それらの合計と平均を求めるVプログラムを書きましょう。 118 | 5. 渡されたintegerの立方数(3乗)を表示するVプログラムを書きましょう。 119 | -------------------------------------------------------------------------------- /jp/examples/section_2/match.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: マッチ 4 | --- 5 | 6 | # マッチ 7 | 8 | ## `match`文 9 | 10 | `match`文は`if - else`文のショートハンドです。 11 | 入力がマッチすると、選択肢の中で最初にマッチした文ブロックを実行し、最後の式を返します。 12 | `else`のブロックは、他の選択肢とマッチしなかった場合に実行されます。 13 | 14 | ```v 15 | num := 1 16 | match num % 2 == 0 { 17 | true { print('The input number is even.') } 18 | else { print('The input number is odd.') } 19 | } 20 | ``` 21 | 22 | `match`を使うと、条件に応じたさまざまな値で変数を初期化することもできます。 23 | 24 | ```v 25 | num := 3 26 | s := match num { 27 | 1 { 'one' } 28 | 2 { 'two' } 29 | else { 30 | 'many' 31 | } 32 | } 33 | ``` 34 | 35 | コード例: 36 | 37 | ```v 38 | fn even(num int) bool { 39 | match num % 2 == 0 { 40 | true { print('The input number is even.') } 41 | else { print('The input number is odd.') } 42 | } 43 | } 44 | 45 | fn num_to_str(num int) int { 46 | match num { 47 | 1 { 'one' } 48 | 2 { 'two' } 49 | else { 50 | 'many' 51 | } 52 | } 53 | } 54 | 55 | fn main() { 56 | println(even(14)) // 'The input number is even.' 57 | println(even(3)) // 'The input number is odd.' 58 | println(num_to_str(1)) // 'one' 59 | println(num_to_str(2)) // 'two' 60 | println(num_to_str(352)) // 'many' 61 | } 62 | ``` 63 | 64 | ### enum 65 | 66 | `.項目名`構文を用いることで、選択肢でenum`の値(`enum`の項目名)とマッチさせることもできます。 67 | 68 | ```v 69 | enum Animal { 70 | cat 71 | dog 72 | goldfish 73 | pig 74 | } 75 | 76 | fn makes_miau(a Animal) bool { 77 | return match a { 78 | .cat { true } // enumの`cat` 79 | else { false } 80 | } 81 | } 82 | 83 | fn is_land_creature(a Animal) bool { 84 | return match a { 85 | .cat { true } // enumの`cat` 86 | .dog { true } // enumの`dog` 87 | .pig { true } // enumの`pig` 88 | else { 89 | false 90 | } 91 | } 92 | } 93 | 94 | // 以下の書き方も可能 95 | fn is_land_creature_alt(a Animal) bool { 96 | return match a { 97 | .goldfish { false } // enumの`goldfish` 98 | else { 99 | true 100 | } 101 | } 102 | } 103 | 104 | fn main() { 105 | my_cat := Animal.cat 106 | my_goldfish := Animal.goldfish 107 | 108 | println(makes_miau(my_cat)) // true 109 | println(is_land_creature(my_cat)) // true 110 | println(is_land_creature(my_goldfish)) // false 111 | } 112 | ``` 113 | 114 | ### Exercises 115 | 116 | 1. 1から50までのすべての偶数の配列を作成するVプログラムを書きましょう。 117 | 2. 数値を持つ配列を渡すと、その中の最大値を返すVプログラムを書きましょう。 118 | 3. color(enum)がredかblueかを調べるVプログラムを書きましょう。 119 | -------------------------------------------------------------------------------- /jp/examples/section_2/operator.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: 演算子 4 | --- 5 | 6 | # 演算子 7 | 8 | Vでサポートされる演算子は以下のとおりです。 9 | 10 | ## 基本演算子 11 | 12 | - `+`(加算)int、float、stringが対象 13 | 14 | - `-`(減算)intとfloatが対象 15 | 16 | - `*`(乗算)intとfloatが対象 17 | 18 | - `/`(除算)intとfloatが対象 19 | 20 | - `%`(剰余)intが対象 21 | 22 | - `=`(代入)値の変更に用いる 23 | 24 | - `:=`(値の初期化) 25 | 26 | ```v 27 | println(3 + 5) 28 | println(2.0 + 5.0) 29 | println('hello' + 'world') 30 | 31 | println(9 - 10) 32 | println(7.0 - 5.0) 33 | 34 | println(3 * 5) 35 | println(2.0 * 4) 36 | 37 | println(23 / 3) 38 | println(25.0 / 5.0) 39 | 40 | println(27 % 5) 41 | println(27 % 3) 42 | ``` 43 | 44 | 上の出力結果 45 | 46 | ```v 47 | 8 48 | 7.0 49 | hello world 50 | 51 | -1 52 | 2.0 53 | 54 | 15 55 | 8.0 56 | 57 | 7 58 | 5.0 59 | 60 | 2 61 | 0 62 | ``` 63 | 64 | > 注意: Vは他の言語と異なり、floatでは剰余`%`を使えません。 65 | 66 | ## 比較演算子 67 | 68 | - `>`: より大きい 69 | 70 | - `<`: より小さい 71 | 72 | - `==`: 等しい 73 | 74 | - `>=`: より大きいか等しい 75 | 76 | - `<=`: より小さいか等しい 77 | 78 | - `!=`: 等しくない 79 | 80 | ## bool演算 81 | 82 | - `&&`: 論理AND演算子 83 | 84 | - `||`: 論理OR演算子 85 | 86 | - `!`: 論理NOT演算子 87 | 88 | ## ビット演算子 89 | 90 | - `<<`: 左ビットシフト 91 | 92 | - `>>`: 右ビットシフト 93 | 94 | - `&`: ビットAND 95 | 96 | - `|`: ビットOR 97 | 98 | - `^`: ビットXOR 99 | 100 | ## 代入演算子 101 | 102 | - `+=`: `foo = foo + var`と同じ 103 | 104 | - `-=`: `foo = foo - var`と同じ 105 | 106 | - `*=`: `foo = foo * var`と同じ 107 | 108 | - `/=`: `foo = foo / var`と同じ 109 | 110 | - `&=`: `foo = foo & var`と同じ 111 | 112 | - `|=`: `foo = foo | var`と同じ 113 | 114 | - `>>=`: `foo = foo >> var`と同じ 115 | 116 | - `<<=`: `foo = foo << var`と同じ 117 | 118 | ## 特殊演算子 119 | 120 | - `in`: メンバーシップで用いる(存在を表す) 121 | 122 | - `none`: optionalで用いる 123 | -------------------------------------------------------------------------------- /jp/examples/section_3/README.md: -------------------------------------------------------------------------------- 1 | # セクション3 2 | 3 | 関数(function)やメソッド(method)、そしてVにおける最も重要なデータ構造である配列(array)や構造体(struct)について学びます。 4 | 5 | - [関数](functions.md) 6 | - [配列](arrays.md) 7 | - [構造体](struct.md) 8 | - [メソッド](methods.md) 9 | -------------------------------------------------------------------------------- /jp/examples/section_3/arrays.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: 配列 4 | --- 5 | 6 | # 配列 7 | 8 | 配列(array)は、メモリ上の連続した位置に保存された項目のコレクションです。配列は、型が同じであるオブジェクトのグループを保存するよう設計された、集約的なデータ構造であり、オブジェクトのシーケンスを保存したりアクセスしたりする場合に最も効率の高いデータ構造です。 9 | 10 | ## 配列を宣言する方法 11 | 12 | **要素の型がintegerの配列を1つ作成する:** 13 | 14 | ```v 15 | mut ages := [18, 25, 37] 16 | 17 | println(ages) 18 | ``` 19 | 20 | 上の出力結果: 21 | 22 | ```console 23 | [18, 25, 37] 24 | ``` 25 | 26 | **要素の型がstringaの配列を1つ作成する:** 27 | 28 | ```v 29 | mut users := ['vbrazo', 'donnisnoni95', 'Delta456'] 30 | 31 | println(users) 32 | ``` 33 | 34 | 上の出力結果: 35 | 36 | ```console 37 | ['vbrazo', 'donnisnoni95', 'Delta456'] 38 | ``` 39 | 40 | > 注意: どの要素もすべて同じ型でなければなりません。以下はコンパイルされません。 41 | 42 | ```go 43 | mut users := ['vbrazo', 'donnisnoni95', 'Delta456', 0] 44 | ``` 45 | 46 | 上の出力結果: 47 | 48 | ``` 49 | ~/main.v:2:43: bad array element type `int` instead of `string` 50 | ``` 51 | 52 | ## 空の配列を作成する 53 | 54 | 宣言で`[]`に続けてデータ型を書くことで、空の配列を1つ作成できます。 55 | 56 | ```v 57 | mut names := []string 58 | mut numbers := []int 59 | ``` 60 | 61 | ## 配列の要素にアクセスする 62 | 63 | ```v 64 | mut users := ['vbrazo', 'donnisnoni95', 'Delta456'] 65 | 66 | println(users[0]) 67 | println(users[2]) 68 | println(users[1]) 69 | ``` 70 | 71 | 上の出力結果: 72 | 73 | ```console 74 | vbrazo 75 | Delta456 76 | donnisnoni95 77 | ``` 78 | 79 | ## 配列の末尾に値を追加する 80 | 81 | `<<`は、配列の末尾に値をひとつ追加する演算子です。 82 | 83 | ```v 84 | mut ages := [18] 85 | ages << 47 86 | 87 | println(ages) 88 | ``` 89 | 90 | 上の出力結果: 91 | 92 | ```console 93 | [18, 47] 94 | ``` 95 | 96 | 値の代わりに配列を追加することもできます。 97 | 98 | ```v 99 | mut ages := [18] 100 | ages << [47, 49] 101 | 102 | println(ages) 103 | ``` 104 | 105 | 上の出力結果 106 | 107 | ```console 108 | [18, 47, 49] 109 | ``` 110 | 111 | ## 配列の長さ 112 | 113 | `.len`メソッドは配列の長さ(つまり要素の数)を返します。 114 | 115 | ```v 116 | mut names := ['Thiago', 'John'] 117 | 118 | println(names.len) 119 | ``` 120 | 121 | 上の出力結果 122 | 123 | ```console 124 | 2 125 | ``` 126 | 127 | ## `in`演算子 128 | 129 | `in`は、要素が配列にあるかどうかをチェックします。 130 | 131 | ```v 132 | mut names := ['Thiago', 'Alex', 'Joe'] 133 | 134 | println('Vitor' in names) 135 | println('Thiago' in names) 136 | ``` 137 | 138 | 上の出力結果 139 | 140 | ```console 141 | false 142 | true 143 | ``` 144 | 145 | ## 配列をスライスする 146 | 147 | Vでは配列を簡単にスライス(切り出し)できます。`slice ()`メソッドを呼ばなくても、Vのデフォルトのスライシング機能だけで配列をスライスできます。 148 | 構文は`配列[開始値..終了値]`のようになります。 149 | 150 | ```v 151 | animals := ['lion', 'goose', 'chicken', 'turkey', 'tiger'] 152 | poultry := animals[1..4] 153 | println(poultry) // ["goose", "chicken", "turkey"] 154 | ``` 155 | 156 | スライスをインデックスの冒頭から開始したい場合、開始値に`0`を置かずに`配列[..終了値]`と書くことも、終了値に`-1`を置かずに`配列[開始値..]`と書くこともできます。 157 | 158 | ```v 159 | x := ['h', 'e', 'l', 'l', 'o'] 160 | y := x[..x.len-1] 161 | z := x[1..] 162 | println(y) // ['h', 'e', 'l', 'l'] 163 | println(z) // ['e', 'l', 'l', 'o'] 164 | ``` 165 | 166 | ## 演習 167 | 168 | 1. 要素をいくつか渡すと配列に保存して出力するVプログラムを書きましょう。 169 | 2. 配列のn番目の値を読み取って逆順で表示するVプログラムを書きましょう。 170 | 3. 配列のすべての要素の合計を求めるVプログラムを書きましょう。 171 | 4. ある配列の要素を別の配列にコピーするVプログラムを書きましょう。 172 | 5. 配列の中で重複している要素の個数を数えるVプログラムを書きましょう。 173 | -------------------------------------------------------------------------------- /jp/examples/section_3/functions.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: 関数 4 | --- 5 | 6 | # 関数 7 | 8 | 関数とは、再利用可能な形に整えられたコードのブロックであり、単一の作業を実行します。 9 | 関数はアプリケーションのモジュラリティを高め、コードをより高度なレベルで再利用できるようにします。 10 | 11 | 理想は、SOLID原則で言うところの[単一責任の原則](https://en.wikipedia.org/wiki/Single_responsibility_principle)に従うことです。この原則は「関数は、そのソフトウェアが提供する機能のひとつの部品についてのみ責任を負うこと」というものであり、コードを今後もメンテナンスできるようにするためのものです。 12 | 13 | CやGoと同様、Vの関数もオーバーライドは禁止されています。 14 | 15 | ```v 16 | fn sum(x, y int) int { 17 | return x + y 18 | } 19 | 20 | println(sum(77, 33)) // 110 21 | ``` 22 | 23 | > 注意: 型名は引数名の後ろに置きます。 24 | 25 | ```v 26 | fn full_name(first_name, last_name string) string { 27 | return first_name + ' ' + last_name 28 | } 29 | 30 | println(full_name("Vitor", "Oliveira")) // Vitor Oliveira 31 | ``` 32 | 33 | ## 可変長引数を取る関数 34 | 35 | 関数は、個数が不定の引数を受け取ることもできます。受け取った可変長引数は配列ではありません。また、受け取った可変長引数を返すこともできません。 36 | 37 | ```v 38 | fn foo(test ...string) { 39 | for txt in test { 40 | println(txt) 41 | } 42 | } 43 | 44 | foo("V", "is", "the", "best", "lang" , "ever") 45 | ``` 46 | 47 | 上の出力結果: 48 | 49 | ```console 50 | V 51 | is 52 | the 53 | best 54 | lang 55 | ever 56 | ``` 57 | 58 | ## 値を複数返す関数 59 | 60 | Goと同様、Vの関数も、型の異なる値を複数返せます。 61 | 62 | ```v 63 | fn student(name string, age int) (string, int) { 64 | return name, age 65 | } 66 | 67 | name, age := student("Tom", 15) 68 | println(name) 69 | println(age) 70 | ``` 71 | 72 | 上の出力結果: 73 | 74 | ```console 75 | Tom, 15 76 | ``` 77 | 78 | ## 高階関数 79 | 80 | Vの関数は、別の関数をパラメータとして受け取ることもできます。これは`sort`や`map`や`filter`といった処理でよく必要になります、 81 | 82 | ```v 83 | fn square(num int) int { 84 | return num * num 85 | } 86 | 87 | fn run(value int, op fn(int) int) int { 88 | return op(value) 89 | } 90 | 91 | println(run(10, square)) // 100 92 | ``` 93 | 94 | ## 命名のルール 95 | 96 | 以下は、関数の命名で守るべきルールの一覧です。 97 | 98 | - 大文字を含んではならない(✖`AlphaTest`) 99 | - 区切り文字にはアンダースコアを用いる(○`hello_world`) 100 | - 名前の冒頭には`_`を置かないこと 101 | - できるかぎり、意味の明快な名前を付けること 102 | - 名前に`__`を含んではならv 103 | - 名前に(種類を問わず)スペース文字を含んではならない 104 | 105 | 上のルールは[`snake_case`](https://en.wikipedia.org/wiki/Snake_case)が由来です。Vではsnake_caseスタイルが用いられ、また推奨されます(読みやすく、書きやすく、理解しやすいため) 106 | 107 | ### 正しい名前 108 | 109 | ```v 110 | fn i_am_valid() 111 | fn thisworkstoo() 112 | fn print_values_through_struct() 113 | ``` 114 | 115 | ### 正しくない名前 116 | 117 | ```v 118 | fn IamNotValid() 119 | fn _print() 120 | fn print__logs() 121 | fn new Make Lexer() 122 | ``` 123 | 124 | ## 演習 125 | 126 | 1. 数値の2乗を求めるVプログラムを関数の形で書きましょう。 127 | 2. 渡された数値が偶数か奇数かをチェックするVプログラムを関数の形で書きましょう。 128 | 3. 10進数を2進数に変換するVプログラムを関数の形で書きましょう。 129 | 4. 渡された数値が素数化どうかをチェックするVプログラムを関数の形で書きましょう。 130 | 5. 渡された配列の要素の最大値を得るVプログラムを関数の形で書きましょう。 131 | 132 | -------------------------------------------------------------------------------- /jp/examples/section_3/methods.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: メソッド 4 | --- 5 | 6 | # メソッド 7 | 8 | Vにはクラスというものはありません。しかし型に対してメソッドを定義できます。 9 | 10 | メソッド(method)とは、1個のレシーバーを特殊な引数として持つ関数であり、指定された型に該当するレシーバーだけがこの関数を実行できます。 11 | レシーバーは、`fn`とメソッド名の間に独自の引数リストを記述します。 12 | 13 | ```v 14 | struct User { 15 | name string 16 | email string 17 | mut: 18 | age int 19 | } 20 | 21 | fn (u User) can_register() bool { 22 | return u.age > 15 23 | } 24 | 25 | fn (u mut User) has_birthday() { 26 | u.age += 1 27 | } 28 | 29 | fn main() { 30 | mut bob := User { 31 | name: 'Bob' 32 | email: 'bob@bob.com' 33 | age: 15 34 | } 35 | alice := User { 36 | name: 'Alice' 37 | email: 'alice@alice-mail.com' 38 | age: 17 39 | } 40 | println(bob.can_register()) 41 | println("Bob needs to be 16 to register, but he only is ${bob.age}.") 42 | println(alice.can_register()) 43 | bob.has_birthday() 44 | println(bob.age) 45 | } 46 | ``` 47 | 48 | 上の出力結果: 49 | 50 | ```console 51 | false 52 | Bob needs to be 16 to register, but he only is 15. 53 | true 54 | 16 55 | ``` 56 | 57 | 上のコードのレシーバー`u`の型は`User`であることがわかります。 58 | ここで`has_birthday()`関数のレシーバーに`mut`が付いていることにご注目ください。データを変更したい場合は`mut`の指定が必要です。 59 | Vのコーディング慣習では、`self`や`this`といったレシーバー名は使いません。1文字のレシーバー名が推奨されます。 60 | 61 | ## 演習 62 | 63 | 1.`Person`型を対象として、未成年かどうかを調べるメソッドを作成しましょう。 64 | 2. `Animal`型について、毛が生えているかどうかを調べるメソッドを作成しましょう。 65 | -------------------------------------------------------------------------------- /jp/examples/section_3/struct.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: 構造体 4 | --- 5 | 6 | # 構造体 7 | 8 | 構造体(struct)は、さまざまなデータ型(レコード)を組み合わせて宣言します。構造体は、さまざまな変数のリストをメモリの1つのブロックの中でひとつの名前で物理的にグループ化することで、単一のポインタでさまざまな変数にアクセスしたり、同じアドレスを返す名前で宣言された構造体にアクセスしたりできます。 9 | 10 | [オブジェクト指向プログラミング](https://ja.wikipedia.org/wiki/%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%E6%8C%87%E5%90%91%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9F%E3%83%B3%E3%82%B0)方面から来た方であれば`class`と見なすこともできなくはありませんが、構造体はより制約が多くなっています。 11 | 12 | ```v 13 | struct User { 14 | name string 15 | email string 16 | country string 17 | } 18 | 19 | fn main() { 20 | user := User { 21 | name: "V developers" 22 | email: "developers@vlang.io" 23 | country: "Canada" 24 | } 25 | 26 | println(user.country) 27 | } 28 | ``` 29 | 30 | > 注意: 構造体は(ヒープではなく)スタックに配置されます。 31 | 32 | 構造体のインスタンスを新たに作成するときには、各フィールドをカンマ`,`で区切ることもできます。これはワンライナーでインスタンスを作成するときに便利です。 33 | 34 | ```v 35 | user := User { name: "V developers", email: "developers@vlang.io", country: "Canada" } 36 | ``` 37 | 38 | ## `&`プレフィックス 39 | 40 | 構造体はヒープに配置して参照することもできます。これを行うには、以下のように`&`プレフィックスを追加します。 41 | 42 | ```v 43 | user := &User{"V developers", "developers@vlang.io", "Canada"} 44 | println(user.name) 45 | ``` 46 | 47 | 変数`user`の型は`&User`になり、`User`への参照となります。 48 | 49 | ## アクセス指定子 50 | 51 | 構造体のフィールドはデフォルトで「private」(モジュールの外からアクセスできない)かつ「イミュータブル」です。これは`pub`や`mut`アクセス指定子で変更できます。 52 | 53 | ```v 54 | struct User { 55 | email string // privateかつイミュータブル(デフォルト) 56 | } 57 | ``` 58 | 59 | `mut:`を指定すると「privateかつミュータブル」にできます。 60 | 61 | ```v 62 | struct User { 63 | email string 64 | mut: 65 | first_name string // privateかつミュータブル 66 | last_name string // (1つのアクセス指定子で複数のフィールドをまとめて指定できる) 67 | } 68 | ``` 69 | 70 | `pub:`を指定すると「publicかつイミュータブル」(リードオンリー)にできます。 71 | 72 | ```v 73 | struct User { 74 | email string 75 | mut: 76 | first_name string 77 | last_name string 78 | pub: 79 | sin_number int // publicかつイミュータブル(リードオンリー) 80 | } 81 | ``` 82 | 83 | `pub mut:`を指定すると「public」かつ「**親モジュール**の中でのみミュータブル」になります。 84 | 85 | ```v 86 | struct User { 87 | email string 88 | mut: 89 | first_name string 90 | last_name string 91 | pub: 92 | sin_number int 93 | pub mut: 94 | phone int // publicだが親モジュールでのみミュータブル 95 | } 96 | ``` 97 | 98 | `__global:`を指定すると、親モジュールの中か外かを問わず「publicかつミュータブル」になります。 99 | 100 | ```go 101 | struct User { 102 | email string 103 | mut: 104 | first_name string 105 | last_name string 106 | pub: 107 | sin_number int 108 | pub mut: 109 | phone int 110 | __global: 111 | address_1 string // 親モジュールの中でも外でもpublicかつミュータブル 112 | address_2 string // (利用を勧めたくないので'__'で始めている) 113 | city string 114 | country string 115 | zip string 116 | } 117 | ``` 118 | 119 | ## 命名のルール 120 | 121 | - `struct`の名前は常に大文字で始めること。 122 | - 構造体の中の変数(フィールド)については[`Snake_Case`](https://github.com/v-community/v_by_example/blob/master/en/examples/section_1/variables.md#naming-rules)にする。 123 | 124 | > 訳注: フィールドのスネークケース縛りは近々変更される可能性あり。 125 | 126 | ## 演習 127 | 128 | 1. `User`の情報を保存して表示する構造体を作成しましょう。 129 | 2. `x`フィールドと`y`フィールドを持つ`Point`構造体を作成し、フィールドをそれぞれprivateとpublicにしましょう。 130 | -------------------------------------------------------------------------------- /jp/examples/section_4/README.md: -------------------------------------------------------------------------------- 1 | # セクション4 2 | 3 | このセクションでは、Arrayオブジェクトの内部機能を詳しく学びます。他にJSON、ファイル入出力、テストの書き方についても扱います。 4 | 5 | - [配列の関数](array-functions.md) 6 | - [テストの書き方](testing.md) 7 | - [ファイル操作](files.md) 8 | - [JSON操作](json.md) 9 | -------------------------------------------------------------------------------- /jp/examples/section_4/array-functions.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: 配列の関数 4 | --- 5 | 6 | # 配列の関数 7 | 8 | ## `repeat` 9 | 10 | 構文 11 | 12 | ```go 13 | array.repeat(number type) 14 | ``` 15 | 16 | 配列の要素を指定の回数だけ繰り返します。 17 | 18 | ```go 19 | foo := [1, 2].repeat(5) 20 | println(foo) // [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] 21 | ``` 22 | 23 | ## `delete` 24 | 25 | 構文 26 | 27 | ```go 28 | array.delete(ix type) 29 | ``` 30 | 31 | インデックス`ix`の位置にある要素を配列から削除します。 32 | 33 | Deletes the element present in the array at index `ix`. 34 | 35 | ```go 36 | mut even_numbers := [2, 4, 6, 8, 10] 37 | even_numbers.delete(3) 38 | println(even_numbers) // [2, 4, 6, 10] 39 | ``` 40 | 41 | ## `reverse` 42 | 43 | 構文 44 | 45 | ```go 46 | array.reverse() 47 | ``` 48 | 49 | 逆順の配列を返します。 50 | 51 | ```go 52 | float_num := [1.1, 1.3, 1.25, 1.4] 53 | float_num.reverse() // [1.4, 1.25, 1.3, 1.1] 54 | ``` 55 | 56 | ## `clone` 57 | 58 | 構文 59 | 60 | ```go 61 | array.clone() 62 | ``` 63 | 64 | 配列を複製して新しい配列を返します。 65 | 66 | ```go 67 | foo := [1, 2, 4, 5, 4, 6] 68 | foo1 := foo.clone() 69 | println(foo1) // [1, 2, 4, 5, 4, 6] 70 | ``` 71 | -------------------------------------------------------------------------------- /jp/examples/section_4/files.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: ファイル操作 4 | --- 5 | 6 | # ファイル操作 7 | 8 | Vでは、ファイルを「プログラムからアクセス可能な任意のファイルオブジェクトの抽象化」としており、`os`ライブラリと深く関連しています。 9 | 10 | ## ファイルの読み込み 11 | 12 | コンピュータサイエンスでは、ファイルの読み込みもさまざまな問題に取り組むうえで重要なタスクです。Vではネイティブの`os`ライブラリで以下のように操作できます。 13 | 14 | ```v 15 | import os 16 | 17 | fn main() { 18 | mut fp := flag.new_flag_parser(os.args) 19 | generator := fp.string('generator', '', 'generator name') 20 | method := fp.string('method', '', 'generator method name') 21 | path := './data/$generator/$method' 22 | 23 | if os.file_exists(path) { 24 | print_generator_sample(path) 25 | } else { 26 | println('File does not exist') 27 | return 28 | } 29 | } 30 | 31 | fn print_generator_sample(path string) { 32 | contents := os.read_file(path.trim_space()) or { 33 | println('Failed to open $path') 34 | return 35 | } 36 | 37 | lines := contents.split_into_lines() 38 | length := lines.len 39 | 40 | print_random_element(lines, length) 41 | } 42 | 43 | fn print_random_element(lines []string, length int) { 44 | rand.seed(time.now().uni) 45 | 46 | println(lines[rand.next(length-1)]) 47 | } 48 | ``` 49 | 50 | ## ファイルへの書き込み 51 | 52 | Vではファイルの書き込みも読み出しと似ています。 53 | 54 | ```v 55 | import os 56 | 57 | fn main() { 58 | path := './data/file.txt' 59 | text := 'Full text description.' 60 | 61 | if contents := os.write_file(path, text) or { 62 | println('Failed while creating file') 63 | return 64 | } 65 | 66 | content_lines = read_file(path) 67 | print(content_lines) 68 | } 69 | 70 | fn read_file(path string) { 71 | contents := os.read_file(path.trim_space()) or { 72 | println('Failed to open $path') 73 | return 74 | } 75 | 76 | return contents.split_into_lines() 77 | } 78 | ``` 79 | 80 | ## 演習 81 | 82 | 1. 中身のあるファイルを1つ作成するVプログラムを書きましょう。 83 | 2. 2つのファイルを読み込んでその中身を表示するVプログラムを書きましょう。 84 | 3. Vの`os`ライブラリを読んで、動作や利用方法を理解してみましょう。 85 | 4. ネストしたJSON文字列をエンコードして結果を新しいファイルに書き出してみましょう。 86 | -------------------------------------------------------------------------------- /jp/examples/section_4/json.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: JSON操作 4 | --- 5 | 6 | # JSON操作 7 | 8 | JSON(JavaScript Object Notation)は、人間にとって読み書きしやすい軽量なデータ交換フォーマットです。コンピュータにとっても生成やパースが容易です。JSONは特定の言語にまったく依存しないので、理想的なデータ交換フォーマットです。 9 | 10 | JSONについて詳しくは、[json.org](http://json.org)をご覧ください。 11 | 12 | ## JSONをパースする 13 | 14 | 他のアプリケーションで受け取ったり既存のアプリケーションで生成したJSON文字列をパースするには以下のようにします。 15 | 16 | ```v 17 | import json 18 | 19 | struct Customer { 20 | first_name string 21 | last_name string 22 | hometown string 23 | } 24 | 25 | fn main() { 26 | customers_string := '[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro" }, { "first_name": "Don", "last_name": "Nisnoni", "hometown": "Kupang" }]' 27 | customers := json.decode([]Customer, customers_string) or { 28 | eprintln('Failed to parse json') 29 | return 30 | } 31 | 32 | // Print the list of customers 33 | for customer in customers { 34 | println('$customer.first_name $customer.last_name: $customer.hometown') 35 | } 36 | } 37 | ``` 38 | 39 | ## JSONを生成する 40 | 41 | 通信やシリアライズで用いるJSON文字列は簡単に生成できます。以下のようにデコード/エンコードできます。 42 | 43 | ```v 44 | import json 45 | 46 | struct Customer { 47 | first_name string 48 | last_name string 49 | hometown string 50 | } 51 | 52 | fn main() { 53 | customer_string := '[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro"}]' 54 | 55 | customer := json.decode([]Customer, customer_string) or { 56 | eprintln('Failed to parse json') 57 | return 58 | } 59 | 60 | encoded_json := json.encode(customer) 61 | 62 | println(encoded_json) 63 | } 64 | ``` 65 | 66 | ## 演習 67 | 68 | 1. 普段使っている言語とVでJSONの扱いがどう違うかを比較してみましょう。 69 | 2. 住所情報を持たせるための`Address`構造体を作りましょう。 70 | 3. `Address`構造体を用いて、JSON形式を含む文字列をデコード/エンコードしましょう。 71 | 4. 2つの構造体`Address`と`User`を作りましょう。1人のuserは複数のaddressを持ちます。続いて、`'[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro", "addresses": [{ street_name: "Rua Princesa Isabel", city: "Rio de Janeiro", country: "Brazil" }] }]'`のようなネストしたJSON文字列を受け取ってデコード/エンコードしましょう。 72 | -------------------------------------------------------------------------------- /jp/examples/section_4/testing.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: テストの書き方 4 | --- 5 | 6 | # テストの書き方 7 | 8 | ソフトウェア開発におけるテストは、コードが特定の要求を満たしていることを確認してアプリケーションが意図したとおりに動作するかどうかを評価したり、製品の品質が期待に沿っているかどうかを調べるために問題点を特定するプロセスです。 9 | 10 | ## テストの自動化 11 | 12 | 自動化されたテストは、問題点を検出する自動化ツールを用いてソフトウェアをテストするプロセスです。プログラマーはテストスクリプトを実行し、自動化ツールを用いてテスト結果を自動生成します。 13 | 14 | ## Vのテスト 15 | 16 | Vのテストファイルはすべて`*_test.v`というファイル形式に揃え、関数名は必ず`test_*`の形式にしなければなりません。 17 | 18 | ```v 19 | // sum.v(sum/サブフォルダ内) 20 | module sum 21 | 22 | pub fn sum(a, b int) int { 23 | return a + b 24 | } 25 | ``` 26 | 27 | ```v 28 | // sum_test.v 29 | import sum 30 | 31 | fn test_sum() { 32 | assert sum.sum(2, 3) == 5 33 | // assert sum.sum(2, 3) == 777 // => sum_test.v:6: FAILED assertion 34 | } 35 | ``` 36 | 37 | 上のテストを実行するには、 `v test_sum.v`を実行します 38 | 39 | ### テストコードの例 40 | 41 | 1. JSON構造のテスト 42 | 43 | ```go 44 | import json 45 | 46 | fn test_encode_customer(){ 47 | customer := Customer{ first_name: "Vitor", last_name: "Oliveira" } 48 | expected := '{ "first_name": "Vitor", "last_name": "Oliveira" }' 49 | 50 | encoded_json := json.encode(customer) 51 | assert encoded_json == expected 52 | } 53 | ``` 54 | 55 | 2. ファイルのテスト 56 | 57 | ```go 58 | import os 59 | 60 | fn test_file_creation() { 61 | file_name := './new_file.txt' 62 | content := 'text' 63 | 64 | os.write_file(file_name, content) 65 | assert content.len == os.file_size(file_name) 66 | 67 | os.rm(file_name) 68 | } 69 | ``` 70 | -------------------------------------------------------------------------------- /pt-br/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribuindo 2 | 3 | ## Geral 4 | 5 | Verifique se sua solicitação de alteração segue as seguintes regras: 6 | 7 | * Novos exemplos ou melhorias nos exemplos existentes são bem-vindos. 8 | * Verifique sua ortografia e gramática. 9 | 10 | ## Adicionando um novo exemplo 11 | 12 | Para adicionar um novo exemplo, crie uma nova pasta e um arquivo ou um arquivo (dependendo do exemplo) no diretório apropriado em `./examples`. Por favor, verifique o arquivo `.plan` para ver quais exemplos planejamos criar. Sinta-se à vontade para trabalhar em quaisquer exemplos pendentes. É um prazer ler/revisar suas alterações e colaborar/codificar com você para incrementa-las em nosso codigo fonte. 13 | 14 | Obrigado por suas contribuições! 15 | 16 | ## Introdução ao projeto 17 | 18 | ### 1. Fork e clone este repositório 19 | 20 | [Fork este repositório](https://github.com/v-community/v_by_example/fork) e clone seu fork. Se você não sabe o que significa fork ou não sabe como fazê-lo, boas instruções estão disponíveis [aqui](https://help.github.com/articles/fork-a-repo/). 21 | 22 | ### 2. Faça as alterações e pressione-as 23 | 24 | Agora você está pronto para fazer as suas alterações! Depois de concluir as alterações, envie essas alterações para o fork e [envie uma **solicitação de recebimento**](https://help.github.com/articles/using-pull-requests/). 25 | 26 | ## Licença 27 | 28 | Este código é gratuito para uso sob os termos da licença MIT. 29 | -------------------------------------------------------------------------------- /pt-br/README.md: -------------------------------------------------------------------------------- 1 | # V por exemplos 2 | 3 | [Brazilian Portuguese](README.md) | [Deutsch](/de/README.md) | [English](/en/README.md) | [Bahasa Indonesia](/id/README.md) | [Chinese](/cn/README.md) 4 | 5 | > Aprenda V por exemplos 6 | 7 | V by Example é uma introdução direta ao V usando exemplos de programas anotados. 8 | 9 | - [Exemplos](examples/README.md) 10 | - [Contribuindo](#contributing) 11 | - [Licença](#license) 12 | 13 | Discord: [https://discord.gg/d3Qk65J](https://discord.gg/d3Qk65J) 14 | 15 | ## Seção 1 16 | 17 | Introdução ao V, apresentando alguns exemplos e exercícios básicos. 18 | 19 | - [Comentários](examples/section_1/comment.md) 20 | - [Palavras-chave](examples/section_1/keywords.md) 21 | - [Primitivos](examples/section_1/primitives.md) 22 | 23 | ## Seção 2 24 | 25 | Esta seção discute os principais operadores e instruções condicionais em V. 26 | 27 | - [Operadores](examples/section_2/operators.md) 28 | 29 | ## Time 30 | 31 | Lista atual de mantenedores/autores: 32 | 33 | - [Don Alfons Nisnoni](https://github.com/dhonx) 34 | - [Ivo-Balbaert](https://github.com/ibalbaert) 35 | - [Sven Patrick Meier](https://github.com/tobyhinloopen) 36 | - [Swastik Baranwal](https://github.com/Delta456) 37 | - [Vitor Oliveira](https://github.com/vbrazo) 38 | 39 | ## Contribuindo 40 | 41 | Veja nosso [CONTRIBUTING.md](CONTRIBUTING.md) e comece a contribuir hoje. Normalmente, elegemos novos mantenedores com base em contribuições. 42 | 43 | ## License 44 | 45 | [MIT](/LICENSE) 46 | -------------------------------------------------------------------------------- /pt-br/examples/README.md: -------------------------------------------------------------------------------- 1 | # Exemplos 2 | -------------------------------------------------------------------------------- /pt-br/examples/section_1/README.md: -------------------------------------------------------------------------------- 1 | # Section 1 2 | -------------------------------------------------------------------------------- /pt-br/examples/section_1/comment.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Comentários 4 | --- 5 | 6 | # Comentários 7 | 8 | V suporta comentários de linha única `//` e comentários de várias linhas `/* [comentários] */`. 9 | Estes tipos de comentários devem ser usados para documentar o código e informar aos outros usuários como o código funciona. 10 | Também podem ser usados para comentar temporariamente o código que deve ser usado posteriormente. 11 | 12 | ```v 13 | // Este é um comentário de linha única 14 | 15 | /* Isto é um 16 | * comentário de várias linhas 17 | * / * Isso também pode ser aninhado * / 18 | * / 19 | ``` 20 | -------------------------------------------------------------------------------- /pt-br/examples/section_1/keywords.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Palavras-chave 4 | --- 5 | 6 | # Palavras-chave 7 | 8 | V é uma linguagem muito pequena, por isso possui poucas palavras-chave. Existem cerca de 25 palavras-chave. 9 | 10 | | Keywords | in | V | Programming | Language | 11 | | -------- | ------ | --- | ----------- | --------- | 12 | | break | const | as | continue | defer | 13 | | else | enum | fn | for | struct | 14 | | go | goto | if | import | return | 15 | | type | pub | mut | in | interface | 16 | | match | module | or | none | | 17 | 18 | Como outras linguagens, as palavras-chave não podem ser usados como uma variável. 19 | -------------------------------------------------------------------------------- /pt-br/examples/section_1/primitives.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Primitivos 4 | --- 5 | 6 | # Primitivos 7 | 8 | V tem menos tipos primitivos que Go. 9 | 10 | ## Tipos básicos 11 | 12 | - bool pode ser `true` ou `false` 13 | 14 | - string 15 | 16 | - inteiro tipo `int` 17 | 18 | - float tipo `float` 19 | 20 | - rune (Unicode string) 21 | 22 | ## Tipos de compostos 23 | 24 | - arrays `[]` 25 | 26 | - map `{}` 27 | 28 | - struct 29 | 30 | ## Inteiro 31 | 32 | O número inteiro é subclassificado em `signed` e `unsigned`. `signed` significa positivo ou negativo e não `unsigned` significa apenas positivo. 33 | 34 | ### Signed Integer 35 | 36 | | Tipo | Tamanho | Range | 37 | | ------ | :------: | --------------------------------------: | 38 | | int8 | 8 bits | -128 to 27 -1 | 39 | | int16 | 16 bits | -215 to 215 - 1 | 40 | | int | 32 bits | -231 to 231 - 1 | 41 | | int64 | 64 bits | -263 to 263 - 1 | 42 | | int128 | 128 bits | -2127 to 2127 - 1 | 43 | 44 | ### Unsigned Integer 45 | 46 | | Tipo | Tamanho | Range | 47 | | ---- | :------: | -----------------------: | 48 | | byte | 8 bits | 0 to 27 -1 | 49 | | u16 | 16 bits | 0 to 215 - 1 | 50 | | u32 | 32 bits | 0 to 231 - 1 | 51 | | u64 | 64 bits | 0 to 263 - 1 | 52 | | u128 | 128 bits | 0 to 2127 - 1 | 53 | -------------------------------------------------------------------------------- /pt-br/examples/section_2/README.md: -------------------------------------------------------------------------------- 1 | # Section 2 2 | -------------------------------------------------------------------------------- /pt-br/examples/section_2/operators.md: -------------------------------------------------------------------------------- 1 | --- 2 | version: 1.0.0 3 | example_title: Operadores 4 | --- 5 | 6 | # Operadores 7 | 8 | V suporta os seguintes operadores: 9 | 10 | ## Operadores básicos 11 | 12 | - `+` (adição) para int, float e string 13 | 14 | - `-` (subtração) para int e float 15 | 16 | - `*` (multiplicação) para int e float 17 | 18 | - `/` (divisão) para int e float 19 | 20 | - `%` (módulos) para int 21 | 22 | - `=` (atribuição) para alterar valores 23 | 24 | - `: =` para inicializar valores 25 | 26 | ```v 27 | println(3+5) 28 | println(2.0+5.0) 29 | println('olá'+'mundo') 30 | 31 | println(9-10) 32 | println(7.0-5.0) 33 | 34 | println(3 * 5) 35 | println(2,0 * 4) 36 | 37 | println(23/3) 38 | println(25.0/5.0) 39 | 40 | println(27%5) 41 | println(27%3) 42 | ``` 43 | 44 | Saída 45 | 46 | ``` 47 | 8 48 | 7.0 49 | Olá Mundo 50 | 51 | -1 52 | 2.0 53 | 54 | 15 55 | 8.0 56 | 57 | 7 58 | 5.0 59 | 60 | 2 61 | 0 0 62 | ``` 63 | 64 | > Nota: Ao contrário de outras linguagens, o V não permite módulo com float. 65 | 66 | ## Operadores de comparação 67 | 68 | - `>` maior que 69 | 70 | - `<` menor que 71 | 72 | - `==` igual a 73 | 74 | - `> =` maior ou igual a 75 | 76 | - `<=` menor ou igual a 77 | 78 | - `! =` não é igual a 79 | 80 | ## Operadores booleanos 81 | 82 | - `&&` e 83 | 84 | - `||` ou 85 | 86 | - `!` não 87 | 88 | ## Operadores bit a bit 89 | 90 | - `<<` left bitshift 91 | 92 | - `>>` right bitshift 93 | 94 | - `&` bitwise and 95 | 96 | - `|` bitwise or 97 | 98 | - `^` bitwise xor 99 | 100 | ## Operadores de atribuições 101 | 102 | - `+ =` o mesmo que `foo = foo + var` 103 | 104 | - `- =` o mesmo que `foo = foo - var` 105 | 106 | - `* =` o mesmo que `foo = foo * var` 107 | 108 | - `/ =` o mesmo que `foo = foo / var` 109 | 110 | - `& =` o mesmo que `foo = foo & var` 111 | 112 | - `| =` o mesmo que `foo = foo | var` 113 | 114 | - `>> =` o mesmo que `foo = foo >> var` 115 | 116 | - `<< =` o mesmo que `foo = foo << var` 117 | 118 | ## Operadores especiais 119 | 120 | - `in` para associação 121 | 122 | - `none` para opcional 123 | --------------------------------------------------------------------------------