Showing preview only (274K chars total). Download the full file or copy to clipboard to get everything.
Repository: v-community/v_by_example
Branch: master
Commit: 339052b909f8
Files: 159
Total size: 211.8 KB
Directory structure:
gitextract_30_ofps6/
├── .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
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/workflows/mdlint.yml
================================================
name: Markdown Lint
on: [push, pull_request]
jobs:
ubuntu-latest:
runs-on: ubuntu-latest
steps:
- name: Installing MarkdownLint CLI
run: sudo npm install -g markdownlint-cli
- uses: actions/checkout@v1
- name: Running MarkdownLint
run: markdownlint **/*.md
================================================
FILE: .gitignore
================================================
*.exe
*.o
*.obj
*.vrepl_temp.v
*.tmp.c
a.out.tmp.c
*.vrepl.v
*.vrepl*
.vrepl_temp
.DS_Store
data/.DS_Store
# examples executable files
src/hello_world/hello_world
src/hello_world/hello_world.exe
main
main.v
================================================
FILE: .markdownlint.json
================================================
{
"MD013": false,
"MD024": false,
"MD033": false,
"MD040": false,
"MD029": false
}
================================================
FILE: .typo-ci.yml
================================================
dictionaries:
- de
- en
- en_GB
- pt_BR
# Files to exclude
excluded_files:
- "*.v"
# Words to exclude
excluded_words:
- typoci
- r'*'
- r'Hello\nWorld'
- variadic
- palavras-chave
- outras
- linguagens
- podem
- ser
- usados
- uma
- linguagem
- muito
- pequena
- por
- possui
- poucas
- Existem
- cerca
- Operadores
- Esta
- discute
- principais
- condicionais
- suporta
- seguintes
- alterar
- valores
- inicializar
- mundo
- outras
- linguagens
- permite
- menor
- maior
- igual
- booleanos
- mesmo
- especiais
- opcional
- Operadores
- Primitivos
- tem
- menos
- tipos
- pode
- ser
- inteiro
- tipo
- compostos
- subclassificado
- significa
- positivo
- negativo
- apenas
- Tamanho
================================================
FILE: .vscode/settings.json
================================================
================================================
FILE: CHANGELOG.md
================================================
# Changelog
## Unreleased
- [PR #66](https://github.com/v-community/v_by_example/pull/66) Update .typo-ci.yml [@dhonx](https://github.com/dhonx)
### Enhancement
- [PR #63](https://github.com/v-community/v_by_example/pull/63) Add Typo CI [@Delta456](https://github.com/Delta456)
- [PR #62](https://github.com/v-community/v_by_example/pull/62) remove unused newline [@Delta456](https://github.com/Delta456)
### Documentation
- [PR #69](https://github.com/v-community/v_by_example/pull/69) using 4 spaces for indentation & format table [@dhonx](https://github.com/dhonx)
- [PR #68](https://github.com/v-community/v_by_example/pull/68) update variadic function, fix typo & improve grammar [@dhonx](https://github.com/dhonx)
- [PR #67](https://github.com/v-community/v_by_example/pull/67) update note section [@dhonx](https://github.com/dhonx)
- [PR #60](https://github.com/v-community/v_by_example/pull/60) fix grammar, formating some code & fix example for loop example [@dhonx](https://github.com/dhonx)
## v0.7.0 (2019-11-03)
- [PR #60](https://github.com/v-community/v_by_example/pull/60) Add testing examples [@vbrazo](https://github.com/vbrazo)
- [PR #61](https://github.com/v-community/v_by_example/pull/63) Add Typo CI [@Delta456](https://github.com/Delta456)
------------------------------------------------------------------------------
## v0.6.0 (2019-11-03)
### Documentation
- [PR #58](https://github.com/v-community/v_by_example/pull/58) add comma and remove some whitespaces [@dhonx](https://github.com/dhonx)
- [PR #57](https://github.com/v-community/v_by_example/pull/57) array: add how to create an empty array [@dhonx](https://github.com/dhonx)
- [PR #41](https://github.com/v-community/v_by_example/pull/41) examples: improve grammar, better MD structure & fix some code [@dhonx](https://github.com/dhonx)
- [PR #40](https://github.com/v-community/v_by_example/pull/40) November and December plan [@vbrazo](https://github.com/vbrazo)
- [PR #38](https://github.com/v-community/v_by_example/pull/38) Improve contributing [@vbrazo](https://github.com/vbrazo)
- [PR #37](https://github.com/v-community/v_by_example/pull/37) Fix broken README links [@vbrazo](https://github.com/vbrazo)
### Feature request
- [PR #59](https://github.com/v-community/v_by_example/pull/59) Add JSON example [@vbrazo](https://github.com/vbrazo)
------------------------------------------------------------------------------
## v0.5.0 (2019-10-24)
### Bug
- [PR #32](https://github.com/v-community/v_by_example/pull/32) More typos [@ksaj](https://github.com/ksaj)
- [PR #31](https://github.com/v-community/v_by_example/pull/31) Exponent typo [@ksaj](https://github.com/ksaj)
### Chores
- [PR #33](https://github.com/v-community/v_by_example/pull/33) Grammar [@ksaj](https://github.com/ksaj)
- [PR #24](https://github.com/v-community/v_by_example/pull/24) Minor fixes [@vbrazo](https://github.com/vbrazo)
- [PR #23](https://github.com/v-community/v_by_example/pull/23) Missing 'or' [@ksaj](https://github.com/ksaj)
### Feature Request
- [PR #26](https://github.com/v-community/v_by_example/pull/26) Follow #25 and more progress [@Delta456](https://github.com/Delta456)
------------------------------------------------------------------------------
## v0.4.0 (2019-10-13)
### Chores
- [PR #23](https://github.com/v-community/v_by_example/pull/23) hello.md: formatting [@dhonx](https://github.com/dhonx)
### Feature Request
- [PR #20](https://github.com/v-community/v_by_example/pull/20) example: functions, arrays, structures etc [@vbrazo](https://github.com/vbrazo)
------------------------------------------------------------------------------
## v0.3.0 (2019-10-12)
### Chores
- [PR #18](https://github.com/v-community/v_by_example/pull/18) update primitives.md [@dhonx](https://github.com/dhonx)
- [PR #17](https://github.com/v-community/v_by_example/pull/17) Update repo structure [@vbrazo](https://github.com/vbrazo)
### Documentation
- [PR #16](https://github.com/v-community/v_by_example/pull/16) Fix Discord link [@vbrazo](https://github.com/vbrazo)
### Feature Request / Enhancement
- [PR #19](https://github.com/v-community/v_by_example/pull/19) example: conditional statements like if, else, else if, for and while [@vbrazo](https://github.com/vbrazo)
------------------------------------------------------------------------------
## v0.2.0 (2019-10-06)
### Feature Request / Enhancement
- [PR #14](https://github.com/v-community/v_by_example/pull/14) Primitives, Variables, Operators and Mutability [@Delta456](https://github.com/Delta456)
## v0.1.1 (2019-09-30)
### Documentation
- [PR #7](https://github.com/v-community/v_by_example/pull/7) Add october.plan [@vbrazo](https://github.com/vbrazo)
- [PR #6](https://github.com/v-community/v_by_example/pull/6) Add CONTRIBUTING [@vbrazo](https://github.com/vbrazo)
- [PR #5](https://github.com/v-community/v_by_example/pull/5) add a final newline at the end of file [@dhonx](https://github.com/dhonx)
### Chores
- [PR #12](https://github.com/v-community/v_by_example/pull/12) ignore executable chores [@dhonx](https://github.com/dhonx)
------------------------------------------------------------------------------
## v0.1.0 (2019-09-26)
### Feature Request / Enhancement
- [PR #1](https://github.com/v-community/v_by_example/pull/1) README.md with first example [@Delta456](https://github.com/Delta456)
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing
## General
Please ensure your pull request adheres to the following guidelines:
* New example or improvements to existing examples are welcome.
* Please check your spelling and grammar.
## A Note on Example Versions
All examples should include the following header:
```markdown
---
version: 3.5.1
example_title: JSON
---
```
Change the `version` attribute according to the following rules:
* MAJOR — You (re)wrote the whole thing. Your new content will need some translation.
* MINOR — Added or removed some content, few sentences, etc.
* PATCH — Spelling, typos. Probably not translated stuff.
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.
## Adding a New Example
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.
Thank you for your contributions!
## Getting started with the project
### 1. Fork and clone this repository
[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/).
#### 2. Make your changes and push them
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/).
## License
This code is free to use under the terms of the MIT license.
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2020 The V Programming Language Community
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# V by Example
**NOTE: This is very outdated and it will be updated and worked upon when V 1.0 is released.**
[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)
> Learn V by Examples
V by Example is a direct introduction to V by using annotated program examples.
- [Examples](#examples)
- [Contributing](#contributing)
- [License](#license)
Discord: [https://discord.gg/vlang](https://discord.gg/vlang)
## Section 1
Introduction to V by presenting a few basic examples and exercises.
- [Hello World](en/examples/section_1/hello_world.md)
- [V Keywords](en/examples/section_1/keywords.md)
- [Primitives](en/examples/section_1/primitives.md)
- [Variables](en/examples/section_1/variables.md)
- [Strings](en/examples/section_1/strings.md)
- [Comment](en/examples/section_1/comment.md)
## Section 2
This section discusses the main operators and conditional statements in V.
- [Operator](en/examples/section_2/operator.md)
- [If-else](en/examples/section_2/if-else.md)
- [Match](en/examples/section_2/match.md)
- [Loops](en/examples/section_2/loops.md)
## Section 3
A study on functions and methods and in the most important data structures in V: arrays and struct.
- [Functions](en/examples/section_3/functions.md)
- [Arrays](en/examples/section_3/arrays.md)
- [Struct](en/examples/section_3/struct.md)
- [Methods](en/examples/section_3/methods.md)
## Section 4
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.
- [Array Functions](en/examples/section_4/array-functions.md)
- [Testing](en/examples/section_4/testing.md)
- [Files](en/examples/section_4/files.md)
- [JSON](en/examples/section_4/json.md)
## Team
Current list of maintainers/authors:
- [Don Alfons Nisnoni](https://github.com/dhonx)
- [Ivo-Balbaert](https://github.com/ibalbaert)
- [Sven Patrick Meier](https://github.com/SuicideS3ason)
- [Swastik Baranwal](https://github.com/Delta456)
- [Vitor Oliveira](https://github.com/vbrazo)
## Contributing
See our [CONTRIBUTING.md](CONTRIBUTING.md) and start contributing today. We usually elect new maintainers based on contributions.
## License
[MIT](LICENSE)
================================================
FILE: SUMMARY.md
================================================
# Table of contents
* [V by Example](README.md)
* [en](en/README.md)
* [examples](en/examples/README.md)
* [section\_3](en/examples/section_3/README.md)
* [Functions](de/examples/section_3/functions.md)
* [Methods](de/examples/section_3/methods.md)
* [Arrays](de/examples/section_3/arrays.md)
* [Struct](de/examples/section_3/struct.md)
* [section\_1](en/examples/section_1/README.md)
* [Primitives](en/examples/section_1/primitives.md)
* [Keywords](en/examples/section_1/keywords.md)
* [Variables](en/examples/section_1/variables.md)
* [Formatted Print](en/examples/section_1/hello_world.md)
* [Strings](en/examples/section_1/strings.md)
* [Comments](en/examples/section_1/comment.md)
* [section\_4](en/examples/section_4/README.md)
* [Files](en/examples/section_4/files.md)
* [JSON](en/examples/section_4/json.md)
* [Testing](en/examples/section_4/testing.md)
* [Array Functions](en/examples/section_4/array-functions.md)
* [section\_2](en/examples/section_2/README.md)
* [Operators](en/examples/section_2/operator.md)
* [Looping Constructs](en/examples/section_2/loops.md)
* [If statement](de/examples/section_2/if-else.md)
* [Match](en/examples/section_2/match.md)
* [V por exemplos](pt-br/README.md)
* [Contribuindo](pt-br/CONTRIBUTING.md)
* [examples](pt-br/examples/README.md)
* [section\_1](pt-br/examples/section_1/README.md)
* [Comentários](pt-br/examples/section_1/comment.md)
* [Primitivos](pt-br/examples/section_1/primitives.md)
* [Palavras-chave](pt-br/examples/section_1/keywords.md)
* [section\_2](pt-br/examples/section_2/README.md)
* [Operadores](pt-br/examples/section_2/operators.md)
* [V mit einem Beispiel](de/README.md)
* [examples](de/examples/README.md)
* [section\_3](de/examples/section_3/README.md)
* [Methods](de/examples/section_3/methods.md)
* [Struct](de/examples/section_3/struct.md)
* [Functions](de/examples/section_3/functions.md)
* [Arrays](de/examples/section_3/arrays.md)
* [section\_4](de/examples/section_4/README.md)
* [Testing](de/examples/section_4/testing.md)
* [Array Functions](de/examples/section_4/array-functions.md)
* [JSON](de/examples/section_4/json.md)
* [Files](de/examples/section_4/files.md)
* [section\_2](de/examples/section_2/README.md)
* [Looping Constructs](de/examples/section_2/loops.md)
* [If statement](de/examples/section_2/if-else.md)
* [Match](de/examples/section_2/match.md)
* [Operators](de/examples/section_2/operator.md)
* [section\_1](de/examples/section_1/README.md)
* [Primitive Datentypen](de/examples/section_1/primitives.md)
* [Schlüsselwörter](de/examples/section_1/keywords.md)
* [Formatted Print](de/examples/section_1/hello_world.md)
* [Strings](de/examples/section_1/strings.md)
* [Kommentare](de/examples/section_1/comment.md)
* [Variables](de/examples/section_1/variables.md)
* [CONTRIBUTING\_de](de/CONTRIBUTING.md)
* [V dengan Contoh](id/README.md)
* [examples](id/examples/README.md)
* [section1](id/examples/section1/README.md)
* [Variabel](id/examples/section1/variables.md)
* [通过例子学V语言](cn/README.md)
* [例子](cn/examples/README.md)
* [section\_3](cn/examples/section_3/README.md)
* [函数](cn/examples/section_3/functions.md)
* [方法](cn/examples/section_3/methods.md)
* [数组](cn/examples/section_3/arrays.md)
* [结构体](cn/examples/section_3/struct.md)
* [section\_1](cn/examples/section_1/README.md)
* [基本类型](cn/examples/section_1/primitives.md)
* [关键字](cn/examples/section_1/keywords.md)
* [变量](cn/examples/section_1/variables.md)
* [print系列函数](cn/examples/section_1/hello_world.md)
* [字符](cn/examples/section_1/strings.md)
* [注释](cn/examples/section_1/comment.md)
* [section\_4](cn/examples/section_4/README.md)
* [文件](cn/examples/section_4/files.md)
* [JSON操作](cn/examples/section_4/json.md)
* [调试](cn/examples/section_4/testing.md)
* [数组函数](cn/examples/section_4/array-functions.md)
* [section\_2](cn/examples/section_2/README.md)
* [运算符](cn/examples/section_2/operator.md)
* [循环结构](cn/examples/section_2/loops.md)
* [If表达式](cn/examples/section_2/if-else.md)
* [匹配](cn/examples/section_2/match.md)
* [コード例で学ぶV言語](jp/README.md)
* [examples](jp/examples/README.md)
* [section\_3](jp/examples/section_3/README.md)
* [関数](jp/examples/section_3/functions.md)
* [メソッド](jp/examples/section_3/methods.md)
* [配列](jp/examples/section_3/arrays.md)
* [構造体](jp/examples/section_3/struct.md)
* [section\_1](jp/examples/section_1/README.md)
* [プリミティブ型](jp/examples/section_1/primitives.md)
* [キーワード](jp/examples/section_1/keywords.md)
* [変数](jp/examples/section_1/variables.md)
* [書式付き出力](jp/examples/section_1/hello_world.md)
* [文字列](jp/examples/section_1/strings.md)
* [コメント](jp/examples/section_1/comment.md)
* [section\_4](jp/examples/section_4/README.md)
* [ファイル操作](jp/examples/section_4/files.md)
* [JSON操作](jp/examples/section_4/json.md)
* [テスト](jp/examples/section_4/testing.md)
* [配列の関数](jp/examples/section_4/array-functions.md)
* [section\_2](jp/examples/section_2/README.md)
* [演算子](jp/examples/section_2/operator.md)
* [ループ](jp/examples/section_2/loops.md)
* [If文](jp/examples/section_2/if-else.md)
* [マッチ](jp/examples/section_2/match.md)
* [Changelog](CHANGELOG.md)
* [Contributing](CONTRIBUTING.md)
* [Documentation Style Guide](docs_style_guide.md)
================================================
FILE: cn/CONTRIBUTING.md
================================================
# 贡献
## 总则
请确保您的请求符合以下准则:
* 欢迎新示例或对现有示例的改进。
* 请检查你的拼写和语法。
## 添加新示例
要添加新示例,请在`./examples`中的相应目录下创建一个新文件夹和一个文件或一个文件(取决于示例)。请检查`.plan`文件,查看我们计划创建哪些示例。请随意处理任何悬而未决的例子。我们很高兴阅读/审阅您的更改,并与您协作/编写代码以合并它们。
谢谢你的贡献!
## 开始贡献项目
### 1. Fork和clone这个repository
[Fork这个repository](https://github.com/v-community/v_by_example/fork) 和clone你的fork. 如果您不知道forking是什么意思或者不知道如何使用它,那么[这里](https://help.github.com/articles/fork-a-repo/) 提供了很好的说明。
### 2. 做出改变并提交它们
现在你准备好做出改变了!完成更改后,将这些更改推送到fork,然后[提交**请求**](https://help.github.com/articles/using-pull-requests/)
## 版权
根据MIT的许可条款,此代码是免费使用的。
================================================
FILE: cn/README.md
================================================
# V举例
[Brazilian Portuguese](/pt-br/README.md) | [Deutsch](/de/README.md) | [English](/en/README.md) | [Bahasa Indonesia](/id/README.md) | [Chinese](README.md)
> Learn V by Examples
V by Example是使用带注释的程序示例对V语言的介绍。
- [例子](#examples)
- [贡献](#contributing)
- [版权](#license)
Discord: [https://discord.gg/d3Qk65J](https://discord.gg/d3Qk65J)
## Section 1
通过一些基本的例子和练习来介绍V语言。
- [Hello World](examples/section_1/hello_world.md)
- [V Keywords](examples/section_1/keywords.md)
- [Primitives](examples/section_1/primitives.md)
- [Variables](examples/section_1/variables.md)
- [Strings](examples/section_1/strings.md)
- [Comment](examples/section_1/comment.md)
## Section 2
本节讨论V语言中主要的运算和条件语句。
- [Operator](examples/section_2/operator.md)
- [If-else](examples/section_2/if-else.md)
- [Match](examples/section_2/match.md)
- [Loops](examples/section_2/loops.md)
## Section 3
学习V语言函数和方法以及最重要的数据结构:数组和结构体
- [Functions](examples/section_3/functions.md)
- [Arrays](examples/section_3/arrays.md)
- [Struct](examples/section_3/struct.md)
- [Methods](examples/section_3/methods.md)
## Section 4
在本节中,我们将深入研究数组对象内部的特征。其他的例子,比如JSON、写/读文件和测试,都会涉及到。
- [Array Functions](examples/section_4/array-functions.md)
- [Testing](examples/section_4/testing.md)
- [Files](examples/section_4/files.md)
- [JSON](examples/section_4/json.md)
## Team
当前维护者/作者列表:
- [Don Alfons Nisnoni](https://github.com/dhonx)
- [Ivo-Balbaert](https://github.com/ibalbaert)
- [Sven Patrick Meier](https://github.com/SuicideS3ason)
- [Swastik Baranwal](https://github.com/Delta456)
- [Vitor Oliveira](https://github.com/vbrazo)
## Contributing
先阅读 [CONTRIBUTING.md](CONTRIBUTING.md) 然后开始贡献. 我们通常根据贡献来选择新的维护者。
## License
[MIT](/LICENSE)
================================================
FILE: cn/examples/README.md
================================================
# 例子
================================================
FILE: cn/examples/section_1/README.md
================================================
# 第一节
================================================
FILE: cn/examples/section_1/comment.md
================================================
---
version: 1.0.0
example_title: 注释
---
# 注释
V支持单行注释`//`和多行注释`/**/`。
它们应该用于记录代码,以便让其他用户知道代码是如何工作的。
它还可以用于临时注释代码,以后必须使用。
```v
// 这是单行注释
/* 这是
* 多行注释
* /* 这也可以嵌套*/
*/
```
================================================
FILE: cn/examples/section_1/hello_world.md
================================================
---
version: 1.0.0
example_title: 格式化打印
---
# 格式化打印
打印由各种I/O流函数处理。人们应该要知道如何去使用它们。
- `print`:用于将文本打印到不带换行符的输出流。
- `println`:与`print`相同,但它会自动追加换行符。
- `eprint`:与`print`相同,但它会输出到错误流(stderr)。
- `eprintln`:与`println`相同,不过它会输出到错误流(stderr)。
- `panic`:程序的输出和退出。
```v
print('Hello World')
print('Hello V')
```
它在屏幕上将会打印 `Hello WorldHello V`
如果要在新行上打印下一行,则必须执行`\n`。
```v
print('Hello World \n')
print('Hello V ')
```
如果不想使用`\n`,则可以使用`println`。
# 注释
V支持单行注释`//`和多行注释`/**/`。
它们应该用于记录代码,以便让其他用户知道代码是如何工作的。
它还可以用于临时注释代码,以后不得不使用。
```v
// 这是单行注释
/* 这是
* 多行注释
* /* 这也可以嵌套*/
*/
```
## 练习
尝试在`hello.v`中删掉代码的注释,看看会发生什么。
================================================
FILE: cn/examples/section_1/keywords.md
================================================
---
version: 1.0.0
example_title: 关键字
---
# 关键字
V是一种非常小巧的语言,所以它很少有关键字。大约有25个关键字。
| Keywords | in | V | Programming | Language |
| -------- | ------ | --- | ----------- | --------- |
| break | const | as | continue | defer |
| else | enum | fn | for | struct |
| go | goto | if | import | return |
| type | pub | mut | in | interface |
| match | module | or | none | |
与其他语言一样,它们不能用作变量。
================================================
FILE: cn/examples/section_1/primitives.md
================================================
---
version: 1.0.0
example_title: Primitives
---
# 基本类型
V的基本类型比Go少。
## 基本数据类型
- bool 也就是 `true` 或者 `false`
- string 字符类型
- 整数类型 `int`
- 浮点数类型 `float`
- rune (Unicode字符串)
## 复合类型
- arrays `[]`
- map `{}`
- struct
## 整数
整数被细分为“signed”和“unsigned”。`signed`表示正或负,`unsigned`仅表示正。
### Signed Integer
| 类型 | 大小 | 范围 |
| ------ | :------: | --------------------------------------: |
| int8 | 8 bits | -128 to 2<sup>7</sup> -1 |
| int16 | 16 bits | -2<sup>15</sup> to 2<sup>15</sup> - 1 |
| int | 32 bits | -2<sup>31</sup> to 2<sup>31</sup> - 1 |
| int64 | 64 bits | -2<sup>63</sup> to 2<sup>63</sup> - 1 |
| int128 | 128 bits | -2<sup>127</sup> to 2<sup>127</sup> - 1 |
### Unsigned Integer
| 类型 | 大小 | 范围 |
| ---- | :------: | -----------------------: |
| byte | 8 bits | 0 to 2<sup>7</sup> -1 |
| u16 | 16 bits | 0 to 2<sup>15</sup> - 1 |
| u32 | 32 bits | 0 to 2<sup>31</sup> - 1 |
| u64 | 64 bits | 0 to 2<sup>63</sup> - 1 |
| u128 | 128 bits | 0 to 2<sup>127</sup> - 1 |
================================================
FILE: cn/examples/section_1/strings.md
================================================
---
version: 1.0.0
example_title: 字符串
---
# 字符串
在V中,可以使用`:=`运算符定义字符串。默认情况下,字符串(与其他变量一样)是不可变的。
一个可以使用`""`或 `''`来表示字符串。使用`vfmt`时,除非包含单引号字符,否则所有双引号字符串都将转换为单引号字符串。
```go
name := 'Bob'
println(name) // Bob
println(name.len) // 3
```
获取字符串的长度使用`.len`。
## 插入
可以在变量前面使用`$`进行字符串插值:
```go
name:= 'Bob'
println('Hello $name!') // Hello Bob!
```
使用`${}`可以有更复杂的插值语法表达式:
```go
struct User {
name string
age int
}
bob := User {
name: 'Bob'
age: 17
}
println('Say Hello to a new User: ${bob.name}, ${bob.age}') // Say Hello to new User: Bob, 17
println('${bob.name}s age is higher or equal to 18: ${bob.age >= 18}') // 0 <=> number representation for false
```
## 连接操作符
使用`+`运算符符字符串会被连接。
```go
text := 'Hello'
concatenated_text := text + ' World!'
println(text) // Hello
println(text + ' World!') // Hello World!
println(concatenated_text) // Hello World!
```
添加到字符串与连接可以使用`+=`运算符。因为字符串在默认情况下是不可变的,所以只有用`mut`声明它们时才能这样做。
```go
mut hello := 'Hello '
hello += 'from V!' // 附加“从V!”到hello中存储的字符串。
println(hello) // Hello from V!
```
在V中,字符串数据使用UTF-8编码,字符串本身是一个只读字节数组。这使得切片成为可能,这意味着我们可以访问单个字符的文本或字符串变量的切片。
```go
robert := 'Robert'
bert := robert[2..robert.len] // bert
rob := robert[0..3] // Rob
println('The persons of interest are: $robert, $bert, $rob') // The persons of interest are: Robert, bert, Rob
```
### Notes
V中的所有运算符两边必须具有相同类型的值。下面的代码无法编译,因为`age`是`int`类型的:
```go
age := 25
println('age = ' + age)
```
因此,我们需要使用`.str()`或使用字符串插值(最好用的方法)将其转换为字符串:
```go
age := 25
println('age = ' + age.str()) // age = 25
println('age = $age') // age = 25
```
要定义字符,可以使用:` `` `。原始字符串可以定义为前缀`r`。
```go
hello := 'Hello\nWorld'
println(hello) // Hello
// World
raw_hello := r'Hello\nWorld'
println(raw_hello) // Hello\nWorld
```
================================================
FILE: cn/examples/section_1/variables.md
================================================
---
version: 1.0.0
example_title: 变量
---
# 变量
在V语言中,变量可以用`:=`运算符声明和初始化。变量只能以这种方式在V中声明,这意味着所有变量都有一个初始值。变量的类型是从右边的值推断出来的。默认情况下,V中的变量是不可变的。
```go
age := 23 // int
name := 'Alice' // string
is_adult := age > 21 // bool
println(age_str) // 23
println(name) // Alice
println(is_adult) // true
```
> Note:变量只能在函数中定义。所以在V中没有全局变量和全局状态。
要更改变量的值,要确保它必须是可变的。这可以在声明变量时使用`mut`关键字来完成。要给变量赋值,可以使用`=`。
```go
mut age := 20 // 声明可变变量age并将其赋给值20。
println(age) // 20
age = 21 // 为age赋个新的值
println(age) // 21
```
在此处省略`mut`关键字将导致错误,因为无法更改不可变变量的值。
```go
fn main() {
age = 20
println(age)
}
```
上面的代码在编译过程中会导致错误,因为未声明变量`age`,
```go
fn main() {
mut age := 20 // 我们声明可变变量age并将其赋给值20。
println(age) // 20
age := 21 // 错误
}
```
这里的`age:=21`在编译时将导致另一个错误,因为变量`age`已在作用域中定义。记住这一点很简单,只要用`:=`声明值并用`=`赋值。
像Go一样,您还可以使用`_`忽略掉不需要的值。通常用于多返回函数。
```go
_ := "I don't need this value"
println(_) // 错误:不能将“_”用作值
```
## Naming Rules
以下是命名变量时应记住的规则。
-名称不应该包含像`AlphaTest`这样的大写字母`
-使用下划线作为分隔符,如`hello_world``
-名称应该尽可能具有描述性
-名称不应该包含`__`
-名称不应该包含任何空格
-如果名称大于11,则必须要使用`_`作为分隔符
这些规则来自[`Snake_Case`](https://en.wikipedia.org/wiki/Snake_Case) V语言使用Snake Case,并且更喜欢它,因为它更易于阅读、书写和理解。
### 有效名称
```go
boby
john_dads
myfamily_number
```
### 无效名称
```go
IamNotValid
new Make
```
================================================
FILE: cn/examples/section_2/README.md
================================================
# 第二节
================================================
FILE: cn/examples/section_2/if-else.md
================================================
---
version: 1.0.0
example_title: If语句
---
# If语句
## `if` 表达式
`if`语句是一个编程条件语句,如果被证明为真,则执行块中给定的代码。下面是V中if语句的一般示例:
```go
john_height := 100
maria_height := 178
if john_height < maria_height {
println("Maria is taller than John")
}
```
在上面的代码中,`println()`只在条件为true时执行。
条件周围不需要括号,并且始终需要大括号。
## `else` 语句
`else`语句是一种编程条件语句,其中当`if`的计算结果为false时,`else`块中的代码将执行。
```go
joey_age := 12
kevin_age := 15
if joey_age > kevin_age {
println("Joey is older")
} else {
println("Kevin is older")
}
```
在本例中,`else`块中的代码将执行,因为`if`中的条件计算结果为`false`。
## `else if` 语句
`if…else`语句根据测试表达式是`true`还是`false`执行两个不同的代码。有时,必须从两种以上的可能性中做出选择。`if……if……else`允许您在多个测试表达式之间进行检查并执行不同的语句。
```go
tom_age := 20
ashia_age := 38
if tom_age < ashia_age {
println("Tom is younger than Ashia")
} else if tom_age > ashia_age {
println("Tom is older than Ashia")
} else {
println("Tom and Ashia are the same age")
}
```
输出
```console
Tom is younger than Asia
```
## 嵌套的 `if..else` 语句
将`if…else`语句嵌套在另一个`if`或`else…if`语句中始终是一个好的做法,这意味着您可以在另一个`if`或`else…if`语句中使用一个`if`、`else`或`else…if`语句。
```go
tom_age := 20
ashia_age := 38
if tom_age < ashia_age {
if tom_age < 18 {
println("tom_age < 18 and younger than Ashia.")
} else {
println("tom_age >= 18 and younger than Ashia.")
}
} else if tom_age > ashia_age {
println("$tom_age > $ashia_age")
} else {
println("$tom_age == $ashia_age")
}
```
输出
```console
tom_age >= 18 and younger than Ashia.
```
## 使用 `if..else` 表达式
`if..else`也可以用作表达式:
```go
tom_age := 20
ashia_age := 38
s := if tom_age < ashia_age {
"Tom is the youngest"
} else {
"Ashia is the youngest"
}
print(s)
```
输出
```console
Tom is the youngest
```
## 练习
1.编写一个V程序来接受两个整数并检查它们是否相等。
2.编写一个V程序来检查给定的数字是偶数还是奇数。
3.编写一个V程序来检查给定的数字是正数还是负数。
4.写一个V程序来确定某一年是否是闰年。
================================================
FILE: cn/examples/section_2/loops.md
================================================
---
version: 1.0.0
example_title: 循环结构
---
# 循环结构
在V语言中只有一种类型的循环,像Go一样,它可以在很多方面使用。
## `for`循环
`for`循环提供了一种快速而简单的方法来重复做一些事情。
如果你想一次又一次地运行相同的代码,每次使用不同的值,它们都很方便。
你可以把一个循环想象成一个电脑版的游戏,告诉某人朝一个方向走X步,然后朝另一个方向走Y步;
例如,“向东走五步”可以用循环的方式来表达:
```go
for i := 0; i < 5; i++ {
println('Walking one step')
}
```
V有`for`循环结构,循环可以用不同的方式编写:
- 数组/映射的`in`运算符
```go
ages := [18, 25, 32, 43, 50]
for age in ages {
println(age)
}
```
> 注意:该值是只读的。
- 带条件的`for`循环
这是一个控制流语句,允许基于给定的布尔条件重复执行代码。
条件周围没有括号,并且始终需要大括号。
```go
mut factorial := 1
mut counter := 1
for {
counter++
if counter > 5 {
println(factorial)
break
}
factorial = factorial * counter
}
println(counter)
```
输出
```console
120
6
```
带有break语句的for循环总是可以缩短代码,方法是将逆条件放在for之后,使其与其他语言中的while语句等价。
```go
mut factorial := 1
mut counter := 1
for counter <= 5 {
factorial = factorial * counter
counter++
}
println(factorial)
println(counter)
```
输出
```console
120
6
```
- 传统的C风格
```go
mut factorial := 1
mut counter := 1
for counter = 1; counter < 6; counter++ {
factorial = factorial * counter
if counter == 5 {
print(factorial)
continue
}
println(counter)
}
```
- 无限循环
`for`循环也能无限循环
```go
for {
println('foo')
}
```
## 练习
1.写一个V程序来显示前10个自然数。
2.编写一个V程序,找出前10个自然数的和。
3.编写一个V程序来打印数组中的整数,并打印它们的平均值。
4.编写一个V程序,从键盘上读出10个数字,求出它们的和和和平均值。
5.编写一个V程序来显示一个整数之前的数的立方。
================================================
FILE: cn/examples/section_2/match.md
================================================
---
version: 1.0.0
example_title: Match
---
# Match
## match语句
match语句是`if-else`的简写方法。
如果输入匹配,将执行第一个匹配分支的语句块,并返回其最后一个表达式。
`else`分支将在没有其他匹配分支时执行。
```v
num := 1
match num % 2 == 0 {
true { print('The input number is even.') }
else { print('The input number is odd.') }
}
```
还可以使用`match`初始化变量,以便根据条件具有不同的值。
```v
num := 3
s := match num {
1 { 'one' }
2 { 'two' }
else {
'many'
}
}
```
例如:
```v
fn even(num int) bool {
match num % 2 == 0 {
true { print('The input number is even.') }
else { print('The input number is odd.') }
}
}
fn num_to_str(num int) int {
match num {
1 { 'one' }
2 { 'two' }
else {
'many'
}
}
}
fn main() {
println(even(14)) // 'The input number is even.'
println(even(3)) // 'The input number is odd.'
println(num_to_str(1)) // 'one'
println(num_to_str(2)) // 'two'
println(num_to_str(352)) // 'many'
}
```
### 枚举
还可以使用`variant`语句将`enum`值(变量)作为分支进行匹配:
```v
enum Animal {
cat
dog
goldfish
pig
}
fn makes_miau(a Animal) bool {
return match a {
.cat { true }
else { false }
}
}
fn is_land_creature(a Animal) bool {
return match a {
.cat { true }
.dog { true }
.pig { true }
else {
false
}
}
}
// OR LIKE THAT
fn is_land_creature_alt(a Animal) bool {
return match a {
.goldfish { false }
else {
true
}
}
}
fn main() {
my_cat := Animal.cat
my_goldfish := Animal.goldfish
println(makes_miau(my_cat)) // true
println(is_land_creature(my_cat)) // true
println(is_land_creature(my_goldfish)) // false
}
```
### 练习
1.编写一个V程序,创建一个从1到50的所有偶数数组。
2.编写一个V程序,给定一个数字数组,返回最大值。
3.编写一个V程序来确定颜色(枚举)是红色还是蓝色
================================================
FILE: cn/examples/section_2/operator.md
================================================
---
version: 1.0.0
example_title: 运算符
---
# 运算符
V支持以下运算符:
## 基本运算符
- `+` (加法) 用于 int, float和string
- `-` (减法) 用于 int和float类型
- `*` (乘法) 用于 int和float类型
- `/` (除法) 用于 int和float类型
- `%` (取模) 用于 int类型
- `=` (赋值) 用于改变值
- `:=` 用于初始化值
```v
println(3 + 5)
println(2.0 + 5.0)
println('hello' + 'world')
println(9 - 10)
println(7.0 - 5.0)
println(3 * 5)
println(2.0 * 4)
println(23 / 3)
println(25.0 / 5.0)
println(27 % 5)
println(27 % 3)
```
输出
```v
8
7.0
hello world
-1
2.0
15
8.0
7
5.0
2
0
```
> 注意:与其他语言不同,V不允许带浮点数的模。
## 比较运算符
- `>`大于
- `<`小于
- `=`等于
- `>=`大于或等于
- `<=`小于或等于
- `!=`不等于
## 布尔运算符
- `&&`和
- `||`或
- `!`非
## 按位运算符
- `<<`左位移
- `>>`右位移
- `&`按位和
- `|`按位或
- `^`按位异或
## 赋值运算符
- `+=`与`foo=foo+var相同`
- `-=`与`foo=foo-var相同`
- `*=`与`foo=foo*var相同`
- `/=`与`foo=foo/var相同`
- `&=`与`foo=foo&var相同`
- `|=`与`foo=foo'var相同`
- `>=`与`foo=foo>>变量相同`
- `<=`与`foo=foo<<var相同`
## 特殊运算符
- `in` for membership
- `none` for optional
================================================
FILE: cn/examples/section_3/README.md
================================================
# 第三节
================================================
FILE: cn/examples/section_3/arrays.md
================================================
---
version: 1.0.0
example_title: 数组
---
# 数组
数组是存储在连续内存位置的项的集合。它是一个聚合数据结构,旨在存储一组相同类型的对象。它是存储和访问一系列对象的最有效的数据结构。
## 如何声明数组
**创建包含整数值的数组:**
```go
mut ages := [18, 25, 37]
println(ages)
```
Output
```console
[18, 25, 37]
```
**或者创建一个包含字符串值的数组:**
```go
mut users := ['vbrazo', 'donnisnoni95', 'Delta456']
println(users)
```
输出
```
['vbrazo', 'donnisnoni95', 'Delta456']
```
> 注意:所有元素必须具有相同的类型。以下代码将无法编译。
```go
mut users := ['vbrazo', 'donnisnoni95', 'Delta456', 0]
```
输出
```
~/main.v:2:43: bad array element type `int` instead of `string`
```
## 创建空数组
如果要创建一个新的空数组,只需声明`[]`,后跟数据类型。
```go
mut names := []string
mut numbers := []int
```
## 访问数组的元素
```go
mut users := ['vbrazo', 'donnisnoni95', 'Delta456']
println(users[0])
println(users[2])
println(users[1])
```
输出
```go
vbrazo
Delta456
donnisnoni95
```
## 将值附加到数组
`<<` 是将值附加到数组末尾的运算符。
```go
mut ages := [18]
ages << 47
println(ages)
```
数组
```go
[18, 47]
```
它还可以附加一个完整的数组。
```go
mut ages := [18]
ages << [47, 49]
println(ages)
```
输出
```
[18, 47, 49]
```
## 数组的长度/大小
`.len` 方法返回数组的长度。
```go
mut names := ['Thiago', 'John']
println(names.len)
```
输出
```
2
```
## In运算符
`in` 检查元素是否在数组中。
```go
mut names := ['Thiago', 'Alex', 'Joe']
println('Vitor' in names)
println('Thiago' in names)
```
输出
```
false
true
```
## 切片
在V中切片很容易,可以使用默认的
V切片功能,无需调用`slice()`方法。
语法如下`my_array[start..end]`
```go
animals := ['lion', 'goose', 'chicken', 'turkey', 'tiger']
poultry := animals[1..4]
println(poultry) // ["goose", "chicken", "turkey"]
```
如果要从索引的开头开始切片,只需将其忽略为放置`0`,然后改`“my_array[…end]`或`my_array[start…]`。
```go
x := ['h', 'e', 'l', 'l', 'o']
y := x[..x.len-1]
z := x[1..]
println(y) // ['h', 'e', 'l', 'l']
println(z) // ['e', 'l', 'l', '0']
```
## 练习
1.编写一个V程序,将元素存储在数组中并打印出来。
2.编写一个V程序,读取数组中n个值,并按相反顺序显示。
3.编写一个V程序来查找数组中所有元素的和。
4.编写一个V程序,将一个数组的元素复制到另一个数组中。
5.编写一个V程序来计算数组中重复元素的总数。
================================================
FILE: cn/examples/section_3/functions.md
================================================
---
version: 1.0.0
example_title: 函数
---
# Functions
函数是一个有组织、可重用的代码块,用于执行单个相关操作。
函数为应用程序提供了更好的模块性和高度的代码重用。
理想情况下,您应该考虑使用[单一责任原则](https://en.wikipedia.org/wiki/single_responsibility_principle) (SOLID),它声明每个模块或功能都应该有责任
对于软件提供的功能的单个部分,以保持代码的可维护性。
像C和Go一样,函数不能重载。
```go
fn sum(x, y int) int {
return x + y
}
println(sum(77, 33)) // 110
```
> 注意:类型在参数名之后。
```go
fn full_name(first_name, last_name string) string {
return first_name + ' ' + last_name
}
println(full_name("Vitor", "Oliveira")) // Vitor Oliveira
```
## 函数变量
函数也可以是可变的,即接受无穷多个参数。
它们不是数组,不能返回。
```go
fn foo(test ...string) {
for txt in test {
println(txt)
}
}
foo("V", "is", "the", "best", "lang" , "ever")
```
输出
```console
V
is
the
best
lang
ever
```
## 多返回函数
与Go类似,V中的函数也可以返回多个不同类型的函数。
```go
fn student(name string, age int) (string, int) {
return name, age
}
name, age := student("Tom", 15)
println(name1)
println(age1)
```
输出
```console
Tom, 15
```
## 高阶函数
V中的函数也可以接受另一个函数作为参数
需要排序、映射、筛选等。
```go
fn square(num int) int {
return num * num
}
fn run(value int, op fn(int) int) int {
return op(value)
}
println(run(10, square)) // 100
```
## 命名规则
以下是命名函数时应记住的规则。
- 名称不应包含像`AlphaTest`这样的大写字母`
- 使用下划线作为分隔符,如`hello_world`
- 名称不应以开头`_`
- 名称应尽可能具有描述性
- 名称不应包含`__`
- 名称不应包含任何空格
这些规则来自[`Snake_Case`](https://en.wikipedia.org/wiki/Snake_Case) V使用Snake Case,并且更喜欢它,因为它更易于阅读、书写和理解。
### 有效名称
```go
fn i_am_valid()
fn thisworkstoo()
fn print_values_through_struct()
```
### 无效名称
```go
fn IamNotValid()
fn _print()
fn print__logs()
fn new Make Lexer()
```
## Exercises
1. Write a V program to find the square of any number using the function.
2. Write a V program to check a given number is even or odd using the function.
3. Write a V program to convert decimal number to binary number using the function.
4. Write a V program to check whether a number is a prime number or not using the function.
5. Write a V program to get the largest element of an array using the function.
================================================
FILE: cn/examples/section_3/methods.md
================================================
---
version: 1.0.0
example_title: Methods
---
# Methods
V没有Class。但是可以为类型定义方法。
方法是一个具有特殊接收器参数的函数,
只有指定类型的接收器才能执行此函数。
接收方在`fn`和方法名之间有自己的参数列表。
```go
struct User {
name string
email string
mut:
age int
}
fn (u User) can_register() bool {
return u.age > 15
}
fn (u mut User) has_birthday() {
u.age += 1
}
fn main() {
mut bob := User {
name: 'Bob'
email: 'bob@bob.com'
age: 15
}
alice := User {
name: 'Alice'
email: 'alice@alice-mail.com'
age: 17
}
println(bob.can_register())
println("Bob needs to be 16 to register, but he only is ${bob.age}.")
println(alice.can_register())
bob.has_birthday()
println(bob.age)
}
```
输出
```console
false
Bob needs to be 16 to register, but he only is 15.
true
16
```
上面的代码实现了两种类型为`User`的接收器`u`的方法。
注意,`has\birthday()`方法有一个mut接收器,这是必需的,因为我们要更改它的数据。
V的惯例不是使用诸如`self、this`之类的接收者名字,而是一个短的,最好是一个只有一个字母的名字。
## 练习
1.为`Person`类型创建一个确定某人是否未成年的方法。
2.创建一个确定`Animal`是否有毛发的方法。
================================================
FILE: cn/examples/section_3/struct.md
================================================
---
version: 1.0.0
example_title: Struct
---
# Struct
struct是一种复合数据类型(或记录)声明,它在内存块中的一个名称下定义物理分组的变量列表,允许通过单个指针或通过返回相同地址的struct声明的名称访问不同的变量。
对于来自[OOP]https://en.wikipedia.org/wiki/Object-oriented_programming) 语言的人来说,它可以被认为是“类”,但有更多的限制。
```go
struct User {
name string
email string
country string
}
fn main() {
user := User {
name: "V developers"
email: "developers@vlang.io"
country: "Canada"
}
println(user.country)
}
```
> 注意:结构是在堆栈上分配的。
创建结构的新实例时,可以使用逗号分隔每个字段。当您想在一行上创建一个新实例时,它很有用。
```go
user := User { name: "V developers", email: "developers@vlang.io", country: "Canada" }
```
## 前缀`&`
您还可以在堆上分配一个结构,并使用`&`前缀获取对它的引用,如下所示:
```go
user := &User{"V developers", "developers@vlang.io", "Canada"}
println(user.name)
```
`user`的类型是`&user`。它是对`User`的引用。
## 访问修饰符
默认情况下,结构字段是`private`和`immutable`。它们的访问修饰符可以用`pub`和`mut`更改。
```go
struct User {
email string // private and immutable (default)
}
```
您可以将它们定义为`private mutable`。
```go
struct User {
email string
mut:
first_name string // private mutable
last_name string // (you can list multiple fields with the same access modifier)
}
```
您还可以将它们定义为`public immutable`(只读)。
```go
struct User {
email string
mut:
first_name string
last_name string
pub:
sin_number int // public immutable (readonly)
}
```
或作为`public`,但仅在父模块中是`mutable`。
```go
struct User {
email string
mut:
first_name string
last_name string
pub:
sin_number int
pub mut:
phone int // public, but mutable only in parent module
}
```
或父模块内外的`public`和`mutable`。
```go
struct User {
email string
mut:
first_name string
last_name string
pub:
sin_number int
pub mut:
phone int
__global:
address_1 string // public and mutable both inside and outside parent module
address_2 string // (not recommended to use, that's why the 'global' keyword
city string // starts with __)
country string
zip string
}
```
## 命名规则
- `struct`的名称应始终为大写。
- 变量命名使用[`Snake_Case`](https://github.com/v-community/v_by_example/blob/master/en/examples/section_1/variables.md#naming-rules) 。
## 练习
1.创建存储和显示“用户”信息的结构。
2.创建一个包含“x”和“y”字段的“Point”结构,并用private和public保护它们。
================================================
FILE: cn/examples/section_4/README.md
================================================
# 第四节
================================================
FILE: cn/examples/section_4/array-functions.md
================================================
---
version: 1.0.0
example_title: 数组函数
---
# 数组函数
## `repeat`
语法
```go
array.repeat(number type)
```
生成具有给定元素次数的数组。
```go
foo := [1, 2].repeat(5)
println(foo) // [1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
```
## `delete`
语法
```go
array.delete(ix type)
```
删除索引`ix`处数组中的元素。
```go
mut even_numbers := [2, 4, 6, 8, 10]
even_numbers.delete(3)
println(even_numbers) // [2, 4, 6, 10]
```
## `reverse`
语法
```go
array.reverse()
```
反转数组。
```go
float_num := [1.1, 1.3, 1.25, 1.4]
float_num.reverse() // [1.4, 1.25, 1.3, 1.1]
```
## `clone`
语法
```go
array.clone()
```
克隆并返回一个新数组。
```go
foo := [1, 2, 4, 5, 4, 6]
foo1 := foo.clone()
println(foo1) // [1, 2, 4, 5, 4, 6]
```
================================================
FILE: cn/examples/section_4/files.md
================================================
---
version: 1.0.0
example_title: 文件操作
---
# 文件操作
V中的文件是程序可访问的任何文件对象的抽象,与`os`库密切相关。
## 读取文件
读取文件是解决计算机科学中几个不同问题的重要任务。为了完成此任务,您可以使用V native library`os`,如下所述:
```go
import os
fn main() {
mut fp := flag.new_flag_parser(os.args)
generator := fp.string('generator', '', 'generator name')
method := fp.string('method', '', 'generator method name')
path := './data/$generator/$method'
if os.file_exists(path) {
print_generator_sample(path)
} else {
println('File does not exist')
return
}
}
fn print_generator_sample(path string) {
contents := os.read_file(path.trim_space()) or {
println('Failed to open $path')
return
}
lines := contents.split_into_lines()
length := lines.len
print_random_element(lines, length)
}
fn print_random_element(lines []string, length int) {
rand.seed(time.now().uni)
println(lines[rand.next(length-1)])
}
```
## 写入文件
在V中写入文件类似于读取文件。
```go
import os
fn main() {
path := './data/file.txt'
text := 'Full text description.'
if contents := os.write_file(path, text) or {
println('Failed while creating file')
return
}
content_lines = read_file(path)
print(content_lines)
}
fn read_file(path string) {
contents := os.read_file(path.trim_space()) or {
println('Failed to open $path')
return
}
return contents.split_into_lines()
}
```
## 练习
1.编写一个V程序来创建一个包含内容的新文件。
2.编写一个V程序来读取两个不同的文件并显示其内容。
3.阅读V中“os”库的工作原理,了解如何使用它。
4.编码一个嵌套的json字符串并用结果编写一个新文件。
================================================
FILE: cn/examples/section_4/json.md
================================================
# JSON
JavaScript对象表示法(JSON)是一种轻量级的数据交换格式,便于人们读写。此外,机器生成和/或解析也同样简单。
JSON完全不依赖于语言,因此它是理想的交换格式。
要了解更多关于JSON的信息,请访问: [json.org](http://json.org).
## 解析JSON
解析由另一个应用程序接收的JSON字符串,或在现有应用程序中生成的JSON字符串:
```go
import json
struct Customer {
first_name string
last_name string
hometown string
}
fn main() {
customers_string := '[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro" }, { "first_name": "Don", "last_name": "Nisnoni", "hometown": "Kupang" }]'
customers := json.decode([]Customer, customers_string) or {
eprintln('Failed to parse json')
return
}
// Print the list of customers
for customer in customers {
println('$customer.first_name $customer.last_name: $customer.hometown')
}
}
```
## 生成JSON
创建用于通信或序列化的JSON字符串也很简单。我们在下面的示例中解码和编码:
```go
import json
struct Customer {
first_name string
last_name string
hometown string
}
fn main() {
customer_string := '[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro"}]'
customer := json.decode([]Customer, customer_string) or {
eprintln('Failed to parse json')
return
}
encoded_json := json.encode(customer)
println(encoded_json)
}
```
## 练习
1.比较您在最喜欢的语言和V中处理JSON的方式。
2.构建包含地址信息的“Address”结构。
3.使用“Address”结构对包含JSON格式的字符串进行解码和编码。
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" }] }]'`,对其进行解码和编码。
================================================
FILE: cn/examples/section_4/testing.md
================================================
---
version: 1.0.0
example_title: 测试
---
# 测试
软件开发中的测试是一个过程,其目的是评估应用程序的功能,以确定代码是否满足指定的要求,并确定问题,以确保产品具有预期的质量。
## 自动化测试
自动化测试遵循使用自动化工具测试软件以发现缺陷的过程。在这个过程中,程序员使用自动化工具执行测试脚本并自动生成测试结果。
## V中的测试
在V中,所有的测试文件都必须使用以下格式命名:`*u test.V`并且函数应该以`test`开头。
```go
// sum.v in subfolder sum
module sum
pub fn sum(a, b int) int {
return a + b
}
```
```go
// sum_test.v
import sum
fn test_sum() {
assert sum.sum(2, 3) == 5
// assert sum.sum(2, 3) == 777 // => sum_test.v:6: FAILED assertion
}
```
要执行测试,应执行`v test_sum.v`。
### 练习
1. 测试JSON结构:
```go
import json
fn test_encode_customer(){
customer := Customer{ first_name: "Vitor", last_name: "Oliveira" }
expected := '{ "first_name": "Vitor", "last_name": "Oliveira" }'
encoded_json := json.encode(customer)
assert encoded_json == expected
}
```
2. 测试文件:
```go
import os
fn test_file_creation() {
file_name := './new_file.txt'
content := 'text'
os.write_file(file_name, content)
assert content.len == os.file_size(file_name)
os.rm(file_name)
}
```
================================================
FILE: code/hello_world/hello.v
================================================
// Single line comments
/* This is a multiline comment.
* /* It can also be nested. */
*
*/
print('Hello V\n')
print('Hello World')
// This will print on a new line automatically
// println('Hello V by Example')
// eprintln('Hello V by Example')
/*println('I am Bob and I am $age old') */ // This won't print because `age` isn't defined.
/* println(foo) */ // Also wouldn't work because custom str func not defined .
//panic('Exiting from the program')
================================================
FILE: code/match-statement/match_examples.v
================================================
fn main() {
numbers := create_even_numbers_to_fifty()
println('Creating an array just containing even numbers from 0 to 50:\n$numbers\n')
println('The maximum of the given array is: ' + max_val(numbers).str())
red_col := Color.red
green_col := Color.green
grey_col := Color.grey
println('The color $green_col is red or blue: ' + is_red_or_blue(green_col).str())
println('The color $red_col is red or blue: ' + is_red_or_blue(red_col).str())
println('The color $grey_col is red or blue: ' + is_red_or_blue(grey_col).str())
println(num_str(2)) // 'two'
println(num_str(5)) // 'many'
}
fn num_str(num int) string {
return match num {
1 { 'one' }
2 { 'two' }
else {
'many'
}
}
}
fn create_even_numbers_to_fifty() []int {
mut numbers := []int{}
for i := 0; i <= 50; i++ {
match i % 2 {
0 { numbers << i }
else {
continue
}
}
}
return numbers
}
fn max_val(numbers []int) int {
mut maximum := 0
for num in numbers {
match num > maximum {
true {
//println('current number: ' + num.str())
maximum = num
}
else { continue }
}
}
return maximum
}
enum Color {
red
blue
green
violet
pink
black
white
gray
grey
purple
yellow
}
fn is_red_or_blue(c Color) bool {
return match c {
.red { true }
.blue { true }
else { false }
}
}
================================================
FILE: code/methods/methods.v
================================================
struct User {
name string
email string
mut:
age int
}
fn (u User) can_register() bool {
return u.age > 15
}
fn (mut u User) has_birthday() { // mut needed to change fields
u.age++
}
// Below function gives error as field email is immutable
// fn (mut u User) change_email() {
// u.email = 'abcd@efgh.com'
// }
fn main() {
mut bob := User {
name: 'Bob'
email: 'bob@bob.com'
age: 15
}
alice := User {
name: 'Alice'
email: 'alice@alice-mail.com'
age: 17
}
println(bob.can_register()) // false
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.
println(alice.can_register()) // true
bob.has_birthday()
println(bob.age) // 16
// alice.has_birthday() // Gives error as alice is immutable
}
================================================
FILE: code/variables/primitives.v
================================================
fn main() {
a:=byte(10)
b:=u16(10000)
c:=u32(1000000)
d:=u64(10000000000)
// e:=u128(10000000000000000000000) // soon
println(typeof(a)) // byte
println(typeof(b)) // u16
println(typeof(c)) // u32
println(typeof(d)) // u64
f := i8(-1)
g := i16(-1000)
h := int(-100000)
i := i64(-1000000000)
// j := i128(-10000000000000000000000000000) // soon
println(typeof(f)) // i8
println(typeof(g)) // i16
println(typeof(h)) // int
println(typeof(i)) // i64
mut k := 100
mut m := byte(10032)
println(typeof(k)) // int
println(typeof(m)) // byte
println(int(m)) // 48
println(m) // 0 (character represented by byte(48))
k = 1000000000000000000 // overflow
println(typeof(k)) // int
println(k) // -1486618624
n := f32(2)
p := f64(2)
mut q := 2.0
println(typeof(n)) // f32
println(typeof(p)) // f64
println(typeof(q)) // f64
println(q) // 2.
q = 1
println(q) // 1.
q = 1.2
println(q) // 1.2
}
================================================
FILE: code/variables/variables.v
================================================
fn main() {
age := 23 // int
name := 'Alice' // string
is_male := false // bool
is_adult := age > 21 // bool
mut email := 'alice@alice-mail.com' //string
mut num_phone := 2 //int
// addr = 'abcd' // error as assignment must be done with :=
// fn := 1 // error as keyword cannot be identifier (see keywords.md)
println(age) // 23
println(name) // Alice
println(is_male) // false
println(is_adult) // true
println(email) // alice@alice-mail.com
println(num_phone) // 2
email = 'alice@other.com' // assigning new value
num_phone += 2 // shorthand assignment
println(email) // alice@other.com
println(num_phone) // 4
// age = 24 // error as it is immutable
// email = 2 // error as RHS (2) is of different type than LHS (email)
}
================================================
FILE: de/CONTRIBUTING.md
================================================
# Contributing
## General
Please ensure your pull request adheres to the following guidelines:
* New example or improvements to existing examples are welcome.
* Please check your spelling and grammar.
## Adding a New Example
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.
Thank you for your contributions!
## Getting started with the project
### 1. Fork and clone this repository
[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/).
#### 2. Make your changes and push them
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/).
## License
This code is free to use under the terms of the MIT license.
================================================
FILE: de/README.md
================================================
# V mit einem Beispiel
[Brazilian Portuguese](/pt-br/README.md) | [Deutsch](README.md) | [English](/en/README.md) | [Bahasa Indonesia](/id/README.md) | [Chinese](/cn/README.md)
> Learn V by Examples
V by Example ist eine Einführung in V anhand von begleitenden, erklärten Codebeispielen.
* [Beispiele](examples/README.md)
* [Contributing](#contributing)
* [License](#license)
Discord: [https://discord.gg/d3Qk65J](https://discord.gg/d3Qk65J)
## Kapitel 1
Eine Einführung in V mit einfachen Beispielen und Aufgaben.
* [Hello World](examples/section_1/hello_world.md)
* [V Schlüsselwörter](examples/section_1/keywords.md)
* [Primitives](examples/section_1/primitives.md)
* [Variablen](examples/section_1/variables.md)
* [Strings](examples/section_1/strings.md)
* [Kommentare](examples/section_1/comment.md)
## Kapitel 2
Dieses Kapitel behandelt bedingte Anweisungen, Schleifen und andere wichtige Operatoren in V.
* [Operatoren](examples/section_2/operator.md)
* [If-else](examples/section_2/if-else.md)
* [Match](examples/section_2/match.md)
* [Schleifen](examples/section_2/loops.md)
## Kaptiel 3
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.
* [Funktionen](examples/section_3/functions.md)
* [Arrays](examples/section_3/arrays.md)
* [Struct](examples/section_3/struct.md)
* [Methoden](examples/section_3/methods.md)
## Kapitel 4
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.
* [Array Funktionen](examples/section_4/array-functions.md)
* [Testing](examples/section_4/testing.md)
* [File-IO](examples/section_4/files.md)
* [JSON](examples/section_4/json.md)
## Team
Derzeitige Liste der Autoren/Maintainer
* [Don Alfons Nisnoni](https://github.com/dhonx)
* [Ivo-Balbaert](https://github.com/ibalbaert)
* [Sven Patrick Meier](https://github.com/SuicideS3ason)
* [Swastik Baranwal](https://github.com/Delta456)
* [Vitor Oliveira](https://github.com/vbrazo)
## Contributing
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.
## Lizenz
[MIT](/LICENSE)
================================================
FILE: de/examples/README.md
================================================
# Examples
================================================
FILE: de/examples/section_1/README.md
================================================
# Section 1
================================================
FILE: de/examples/section_1/comment.md
================================================
---
version: 1.0.0
example_title: Kommentare
---
# Kommentare
V bietet die Möglichkeit Zeilenkommentare mit `//` und mehrzeilige Kommentare mit `/* */` zu erzeugen.
Kommentare sollen genutzt werden, um den Code zu dokumentieren, sodass andere verstehen können was dieser Teil des Codes tut.
Kommentare in V können auch ineinander geschachtelt sein.
```v
// Das ist ein Zeilenkommentar
/* Das hier ist ein
* mehrzeiliger Kommentar
* /* Dieser Kommentar wurde in den mehrzeiligen Kommentar geschachtelt. */
*/
```
================================================
FILE: de/examples/section_1/hello_world.md
================================================
---
version: 1.0.0
example_title: Formatted Print
---
# Formatted Print
Konsolenausgaben werden durch verschiedene I/O-Streams gehandhabt, dazu sollte man wissen, wo und wie sie zu verwenden sind.
- `print`: schreibt Text in den Standard output stream (stdout), ohne einen Zeilenumbruch am Ende.
- `println`: wie `print`, allerdings mit Zeilenumbruch am Ende.
- `eprint`: wie `print`, aber der Output geht durch den Standard Error Stream (stderr).
- `eprintln`: wie `eprint`, aber mit einem Zeilenumbruch am Ende.
- `panic`: gibt den übergebenen Text auf der Konsole aus und beendet das Programm mit Fehlerode 1.
```v
print('Hello World')
print('Hello V')
```
Dieses Programm erzeugt die folgende Ausgabe in der Konsole: `Hello WorldHello V`
Wenn man die nächste Zeile in einer neuen Zeile ausgeben möchte, muss man am Ende des Satzes ein `\n` hinzufügen.
```v
print('Hello World \n')
print('Hello V ')
```
Wenn man `\n` nicht verwenden möchte, dann kann man statt `print` auch `println` verwenden.
## Exercises
Entkommentiere den Code in `hello.v` und sieh was passiert.
================================================
FILE: de/examples/section_1/keywords.md
================================================
---
version: 1.0.0
example_title: Schlüsselwörter
---
# Schlüsselwörter
V ist eine kleine Programmiersprache mit wenigen Schlüsselwörtern (circa 23 Stück).
| Schlüsselwörter | der | Programmiersprache | V | |
| --------------- | ------ | ------------------ | -------- | --------- |
| break | const | as | continue | defer |
| else | enum | fn | for | struct |
| go | goto | if | import | return |
| type | pub | mut | in | interface |
| match | module | or | none | |
Wie in anderen Programmiersprachen können Schlüsselwörter nicht als Variablenbezeichner verwendet werden.
================================================
FILE: de/examples/section_1/primitives.md
================================================
---
version: 1.0.0
example_title: Datentypen
---
# Primitive Datentypen
V hat weniger primitive Datentypen als Go.
## Grundlegende Typen
- `bool`: Wahrheitswert `true` oder `false`
- `string`: eine Zeichenkette aus Bytes
- `int`: numerischer Typ für ganze Zahlen
- `float` numerischer Typ für Gleitkommazahlen.
- `rune`: Unicode string, ein character literal
## Komplexere Typen
- `array`/`[]`: Eine Sammlung von Elementen des selben Typs (siehe [Array](../section_3/arrays.md)).
- `map`: Eine Sammlung von Schlüssel- und Wertpaaren `{ 'key' : value }`
- `struct`: Eine Datenstruktur zur Modellierung komplexerer Daten (siehe [Structs](../section_3/struct.md)).
## Integer
Der Typ Integer kann weiterhin unterschieden werden in `signed` und `unsigned`. `Signed` bedeutet vorzeichenbehaftet, also positive und negative Werte der Variable sind möglich.
`Unsigned` hingegen hat kein Vorzeichen, demnach kann der Wert nur eine positive Zahl sein.
### Signed Integer
| Type | Größe | Wertbereich |
| ------ | :------: | ---------------------------------------: |
| int8 | 8 bits | -128 bis 2<sup>7</sup> -1 |
| int16 | 16 bits | -2<sup>15</sup> bis 2<sup>15</sup> - 1 |
| int | 32 bits | -2<sup>31</sup> bis 2<sup>31</sup> - 1 |
| int64 | 64 bits | -2<sup>63</sup> bis 2<sup>63</sup> - 1 |
| int128 | 128 bits | -2<sup>127</sup> bis 2<sup>127</sup> - 1 |
### Unsigned Integer
| Type | Size | Wertbereich |
| ---- | :------: | ------------------------: |
| byte | 8 bits | 0 bis 2<sup>7</sup> -1 |
| u16 | 16 bits | 0 bis 2<sup>15</sup> - 1 |
| u32 | 32 bits | 0 bis 2<sup>31</sup> - 1 |
| u64 | 64 bits | 0 bis 2<sup>63</sup> - 1 |
| u128 | 128 bits | 0 bis 2<sup>127</sup> - 1 |
================================================
FILE: de/examples/section_1/strings.md
================================================
---
version: 1.0.0
example_title: Strings
---
# Strings
In V können Strings mit dem Deklarationsoperator (`:=`) deklariert und initialisiert werden und sind, wie andere Variablen in V auch, standardmäßig `immutable`, d.h. unveränderlich.
Man kann zur Definition einer Variable vom Typ `string` sowohl doppelte (`""`), als auch einfache (`''`) Anführungszeichen verwenden.
Bei der Verwendung von `vfmt` werden doppelte Anführungszeichen in einzelne Anführungszeichen konvertiert, es sei denn der String enthält einzelne Anführungszeichen.
```go
name := 'Bob'
println(name) // Bob
println(name.len) // 3
```
Um die Länge eines Strings zu ermitteln, kann man die `.len` Methode verwenden.
## String Interpolation
Es ist ebenfalls möglich Variablen in einen String zu verpacken und diesen damit zu "erweitern" (engl. _interpolation = Erweiterung_). Um eine Variable in einen String zu interpolieren, verwendet man `$` vor dem Variablennamen:
```go
name:= 'Bob'
println('Hello $name!') // Hello Bob
```
Um komplexere Ausdrücke zu interpolieren kann man nach dem Dollarzeichen noch geschweifte Klammern hinzufügen (`${}`), um so den Ausdruck darin zu interpolieren.
```go
struct User {
name string
age int
}
bob := User {
name: 'Bob'
age: 17
}
println('Say Hello to a new User: ${bob.name}, ${bob.age}') // Say Hello to new User: Bob, 17
println('${bob.name}s age is higher or equal to 18: ${bob.age >= 18}') // 0 <=> number representation for false
```
## Konkatenation
Strings können mittels des `+` Operators auch aneinander gehängt (konkateniert) werden.
Da Strings ebenfalls standardmäßig unveränderlich sind, kann man nur Strings konkatenieren, die mit dem `mut` Schlüsselwort deklariert und initialisiert wurden.
```go
mut text := 'Hello'
concatenated_text := text + ' World!'
println(text) // Hello
println(text + ' World!') // Hello World!
println(concatenated_text) // Hello World!
```
Das Anhängen von `string`s kann man entweder mit Konkatenation oder dem `+=` Operator erreichen.
```go
mut hello := 'Hello '
hello += 'from V!' // appends 'from V!' to the string stored in hello.
println(hello) // Hello from V!
```
In V werden die Daten eines Strings in UTF-8 codiert, der String wird dann als schreibgeschützes Byte-Array repräsentiert.
```go
robert := 'Robert'
bert := robert[2..robert.len-1] // bert
rob := robert[0..3] // Rob
println('The persons of interest are: $robert, $bert, $rob') // The persons of interest are: Robert, bert, Rob
```
### Notizen
Unter Verwendung `some_string[start..end]` Syntax, muyss beachtet werden, dass `end` nicht mehr enthalten ist.
Alle Operatoren in V können nur verwendet werden, wenn auf beiden Seiten des Operators Variablen des selben Typs stehen.
Der nachstehende Code kann nicht kompiliert werden, weil `age` vom Typ `int` ist.
```go
age := 25
println('age = ' + age)
```
Daher muss die Variable zuerst mit Hilfe der `.str()` Funktion in einen String konvertiert werden, oder man verwendet String-Interpolation (empfohlener Ansatz).
```go
age := 25
println('age = ' + age.str()) // age = 25
println('age = $age') // age = 25
```
Es können weiterhin auch Character literals mit ` `` ` definiert werden.
Zusätzlich gibt es die Möglichkeit sogenannte Raw-Strings mit einem vorangestellten `r` zu definieren, diese werden nicht "escaped".
```go
hello := 'Hello\nWorld'
println(hello) // Hello
// World
raw_hello := r'Hello\nWorld'
println(raw_hello) // Hello\nWorld
```
================================================
FILE: de/examples/section_1/variables.md
================================================
---
version: 1.0.0
example_title: Variables
---
# Variables
Variablen können in V mit dem `:=` Operator deklariert und initialisiert werden.
Das ist die einzige Möglichkeit Variablen in V zu erzeugen, daraus folgt, dass alle Variablen in V immer einen initialen Wert haben.
Der Typ der Variable wird aus dem Wert auf der rechten Seite der Zuweisung abgeleitet. Variablen in V sind immutable per default.
```go
age := 23 // int
name := 'Alice' // string
is_adult := age > 21 // bool
println(age_str) // 23
println(name) // Alice
println(is_adult) // true
```
**Merke:** Variablen können nur innerhalb einer Funktion definiert werden. Es gibt in V keine globalen Variablen und auch keinen globalen Programmzustand.
Um den Wert einer Variable zu ändern muss diese mutable sein. Dies kann durch hinzufügen von `mut` zur Deklaration erreicht werden.
Einen neuen Variablenwert kann man dann mit `=` setzen.
```go
mut age := 20 // we declare the mutable variable age and assign it to the value 20.
println(age) // 20
age = 21 // we assign a new value to age
println(age) // 21
```
Das Weglassen des `mut` Schlüsselworts hier resultiert in einem Fehler beim Kompilieren, denn der Wert einer immutable Variable kann nicht verändert werden.
```go
fn main() {
age = 20
println(age)
}
```
Der obenstehende Code würde ebenfalls in einem Fehler beim kompilieren resultieren, da die Variable `age` hier nicht definiert ist,
```go
fn main() {
mut age := 20 // we declare the mutable variable age and assign it to the value 20.
println(age) // 20
age := 21 // ERROR
}
```
Hier würde `age := 21` einen Fehler beim kompilieren erzeugen, denn `age` ist hier schon definiert und kann nicht neu deklariert werden.
Eine Variable anlegen: `:=`.
Einen neuen Wert zuweisen: `=`.
================================================
FILE: de/examples/section_2/README.md
================================================
# Section 2
================================================
FILE: de/examples/section_2/if-else.md
================================================
---
version: 1.0.0
example_title: If statement
---
# If statement
## The `if` statement
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:
```go
john_height := 100
maria_height := 178
if john_height < maria_height {
println("Maria is taller than John")
}
```
In the above code, `println()` will only execute when the condition is true.
There are no parentheses needed for surrounding the condition, and the braces are always required.
## The `else` statement
An `else` statement is a programming conditional statement in which when `if` evaluates to false then the code in `else` block executes.
```go
joey_age := 12
kevin_age := 15
if joey_age > kevin_age {
println("Joey is older")
} else {
println("Kevin is older")
}
```
In this example, the code inside the `else` block will execute because the condition in `if` evaluates to `false`.
## The `else if` statement
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.
```go
tom_age := 20
ashia_age := 38
if tom_age < ashia_age {
println("Tom is younger than Ashia")
} else if tom_age > ashia_age {
println("Tom is older than Ashia")
} else {
println("Tom and Ashia are the same age")
}
```
Output
```
Tom is younger than Asia
```
## Nested `if..else` statement
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.
```go
tom_age := 20
ashia_age := 38
if tom_age < ashia_age {
if tom_age < 18 {
println("tom_age < 18 and younger than Ashia.")
} else {
println("tom_age >= 18 and younger than Ashia.")
}
} else if tom_age > ashia_age {
println("$tom_age > $ashia_age")
} else {
println("$tom_age == $ashia_age")
}
```
Output
```
tom_age >= 18 and younger than Ashia.
```
## Using `if..else` as expression
The `if..else` can also be used as an expression:
```go
tom_age := 20
ashia_age := 38
s := if tom_age < ashia_age {
"Tom is the youngest"
} else {
"Ashia is the youngest"
}
print(s)
```
Output
```
Tom is the youngest
```
## Exercises
1. Write a V program to accept two integers and check whether they are equal or not.
2. Write a V program to check whether a given number is even or odd.
3. Write a V program to check whether a given number is positive or negative.
4. Write a V program to find whether a given year is a leap year or not.
================================================
FILE: de/examples/section_2/loops.md
================================================
---
version: 1.0.0
example_title: Looping Constructs
---
# Looping Constructs
There's only one type of loop in V language, like Go which can be used in many ways.
## `for` loop
`for` loops offer a quick and easy way to do something repeatedly.
They're handy, if you want to run the same code over and over again, each time with a different value.
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;
for example, the idea "Go five steps to the east" could be expressed this way as a loop:
```go
for i := 0; i < 5; i++ {
println('Walking one step')
}
```
V has the `for` looping construct and the loop can be written in different ways:
1. `in` operator for array/map
```go
ages := [18, 25, 32, 43, 50]
for age in ages {
println(age)
}
```
> Note: The value is read-only.
2. `for` loop with a condition
This is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.
There are no parentheses surrounding the condition, and the braces are always required.
```go
mut factorial := 1
mut counter := 1
for {
counter++
if counter > 5 {
println(factorial)
break
}
factorial = factorial * counter
}
println(counter)
```
Output
```
120
6
```
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.
```go
mut factorial := 1
mut counter := 1
for counter <= 5 {
factorial = factorial * counter
counter++
}
println(factorial)
println(counter)
```
Output
```
120
6
```
3. Traditional C style
```go
mut factorial := 1
mut counter := 1
for counter = 1; counter < 6; counter++ {
factorial = factorial * counter
if counter == 5 {
print(factorial)
continue
}
println(counter)
}
```
4. Infinite Loop
`for` loop can also be infinite
```go
for {
println('foo')
}
```
## Exercises
1. Write a V program to display the first 10 natural numbers.
2. Write a V program to find the sum of first 10 natural numbers.
3. Write a V program to print the integers inside an array and also print their mean.
4. Write a V program to read 10 numbers from keyboard and find their sum and average.
5. Write a V program to display the cube of the number upto given an integer.
================================================
FILE: de/examples/section_2/match.md
================================================
---
version: 1.0.0
example_title: Match
---
# Match
## The `match` statement
A match statement is a short-hand way for `if - else`.
If the input is matched the statement block of the first matching branch will be executed and its last expression will be returned.
The `else` branch will be executed when there is no other matching branch.
```v
num := 1
match num % 2 == 0 {
true { print('The input number is even.') }
else { print('The input number is odd.') }
}
```
One can also initialize variables using `match` to have different values according to a condition.
```v
num := 3
s := match num {
1 { 'one' }
2 { 'two' }
else {
'many'
}
}
```
Examples:
```v
fn even(num int) bool {
match num % 2 == 0 {
true { print('The input number is even.') }
else { print('The input number is odd.') }
}
}
fn num_to_str(num int) int {
match num {
1 { 'one' }
2 { 'two' }
else {
'many'
}
}
}
fn main() {
println(even(14)) // 'The input number is even.'
println(even(3)) // 'The input number is odd.'
println(num_to_str(1)) // 'one'
println(num_to_str(2)) // 'two'
println(num_to_str(352)) // 'many'
}
```
### Enums
One can also match on `enum` values (variants) as branches by using the `.variant_here` syntax:
```v
enum Animal {
cat
dog
goldfish
pig
}
fn makes_miau(a Animal) bool {
return match a {
.cat { true }
else { false }
}
}
fn is_land_creature(a Animal) bool {
return match a {
.cat { true }
.dog { true }
.pig { true }
else {
false
}
}
}
// OR LIKE THAT
fn is_land_creature_alt(a Animal) bool {
return match a {
.goldfish { false }
else {
true
}
}
}
fn main() {
my_cat := Animal.cat
my_goldfish := Animal.goldfish
println(makes_miau(my_cat)) // true
println(is_land_creature(my_cat)) // true
println(is_land_creature(my_goldfish)) // false
}
```
### Exercises
1. Write a V program that creates an array of all even numbers from 1 to 50.
2. Write a V program that, given an array of numbers, returns the maximum value.
3. Write a V program that determines whether color (enum) is red or blue
================================================
FILE: de/examples/section_2/operator.md
================================================
---
version: 1.0.0
example_title: Operators
---
# Operators
V bietet die folgenden Operatoren:
## Grundlegende Operatoren
- `+`:
- Arithmetik: Addition von `int`, `float`
- `string`-Konkatenation.
- `-` Subtraktion von `int` und `float`.
- `*` Multiplikation von `int` und `float`.
- `/` Division von `int` und `float`.
- `%` Modulo-operator: Ganzzahlige Teilung mit Rest `int`.
- `=` Zuweisung eines Wertes für eine Variable.
- `:=` Deklaration und Initialisierung einer Variable.
```v
println(3 + 5)
println(2.0 + 5.0)
println('hello' + 'world')
println(9 - 10)
println(7.0 - 5.0)
println(3 * 5)
println(2.0 * 4)
println(23 / 3)
println(25.0 / 5.0)
println(27 % 5)
println(27 % 3)
```
Output
```v
8
7.0
hello world
-1
2.0
15
8.0
7
5.0
2
0
```
> Bemerkung: Im Gegensatz zu anderen (Programmier-) Sprachen kann der `Modulo`-operator (`%`) in V nicht mit `floats` angewandt werden.
## Vergleichsoperatoren
- `>` größer als
- `<` kleiner als
- `==` gleich
- `>=` größer oder gleich
- `<=` kleiner oder gleich
- `!=` ungleich
## Boolsche Operatoren
- `&&` logisches und
- `||` logisches oder
- `!` logisches nicht
## Bitwise Operators
- `<<` bitshift links
- `>>` bitshift rechts
- `&` bitweises Und
- `|` bitweises Oder
- `^` bitweises XOR (exklusives Oder)
## Zuweisungsoperatoren
- `+=` ist äquivalent zu `foo = foo + var`
- `-=` ist äquivalent zu `foo = foo - var`
- `*=` ist äquivalent zu `foo = foo * var`
- `/=` ist äquivalent zu `foo = foo / var`
- `&=` ist äquivalent zu `foo = foo & var`
- `|=` ist äquivalent zu `foo = foo | var`
- `>>=` ist äquivalent zu `foo = foo >> var`
- `<<=` ist äquivalent zu `foo = foo << var`
## Spezielle Operatoren
- `in`: für eine Prüfung ob ein Element Teil einer Sammlung ist.
- `none`: zur Prüfung, ob ein Wert gesetzt wurde.
================================================
FILE: de/examples/section_3/README.md
================================================
# Section 3
================================================
FILE: de/examples/section_3/arrays.md
================================================
---
version: 1.0.0
example_title: Arrays
---
# Arrays
An array is a collection of items stored in contiguous memory locations. It's an aggregate data structure that is designed to store a group of objects of the same type. It's the most efficient data structure for storing and accessing a sequence of objects.
## How to declare an array
**Create an array that holds integer values:**
```go
mut ages := [18, 25, 37]
println(ages)
```
Output
```
[18, 25, 37]
```
**Or create an array that holds string values:**
```go
mut users := ['vbrazo', 'donnisnoni95', 'Delta456']
println(users)
```
Output
```
['vbrazo', 'donnisnoni95', 'Delta456']
```
> Note: All elements must have the same type. The following code will not compile.
```go
mut users := ['vbrazo', 'donnisnoni95', 'Delta456', 0]
```
Output
```
~/main.v:2:43: bad array element type `int` instead of `string`
```
## Create an empty array
If you want to create a new empty array, just declare `[]` followed by the data type.
```go
mut names := []string
mut numbers := []int
```
## Accessing element of the array
```go
mut users := ['vbrazo', 'donnisnoni95', 'Delta456']
println(users[0])
println(users[2])
println(users[1])
```
Output
```go
vbrazo
Delta456
donnisnoni95
```
## Append a value to an array
`<<` is an operator that appends a value to the end of the array.
```go
mut ages := [18]
ages << 47
println(ages)
```
Output
```go
[18, 47]
```
It can also append an entire array.
```go
mut ages := [18]
ages << [47, 49]
println(ages)
```
Output
```
[18, 47, 49]
```
## Length/size of an array
`.len` method returns the length of the array.
```go
mut names := ['Thiago', 'John']
println(names.len)
```
Output
```
2
```
## In operator
`in` check if an element is inside an array.
```go
mut names := ['Thiago', 'Alex', 'Joe']
println('Vitor' in names)
println('Thiago' in names)
```
Output
```
false
true
```
## Slicing an array
It's easy to slice an array in V. You can slice an array with the default
V slicing feature without having to call the `slice ()` method.
The syntax is like this `my_array[start..end]`
```go
animals := ['lion', 'goose', 'chicken', 'turkey', 'tiger']
poultry := animals[1..4]
println(poultry) // ["goose", "chicken", "turkey"]
```
If you want to slice from the start of the index, just ignore it to put `0` and using instead `my_array[..end]` or `my_array[start..]`.
```go
x := ['h', 'e', 'l', 'l', 'o']
y := x[..x.len-1]
z := x[1..]
println(y) // ['h', 'e', 'l', 'l']
println(z) // ['e', 'l', 'l', '0']
```
## Exercises
1. Write a V program to store elements in an array and print it.
2. Write a V program to read n number of values in an array and display it in reverse order.
3. Write a V program to find the sum of all elements of the array.
4. Write a V program to copy the elements of one array into another array.
5. Write a V program to count a total number of duplicate elements in an array.
================================================
FILE: de/examples/section_3/functions.md
================================================
---
version: 1.0.0
example_title: Functions
---
# Functions
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.
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
for a single part of the functionality provided by the software to keep your code maintainable.
Like C and Go, functions cannot be overloaded.
```go
fn sum(x, y int) int {
return x + y
}
println(sum(77, 33))
```
> Note: The type comes after the argument's name.
```go
fn full_name(first_name, last_name string) string {
return first_name + ' ' + last_name
}
println(full_name("Vitor", "Oliveira"))
```
## Variadic Functions
Functions can also be variadic i.e. accept an infinite number of arguments.
They are not arrays and cannot be returned.
```go
fn foo(test ...string) {
for txt in test {
println(txt)
}
}
foo("V", "is", "the", "best", "lang" , "ever")
```
Output
```
V
is
the
best
lang
ever
```
## Multi-Return Functions
Similar to Go, functions in V can also return multiple and with a different type.
```go
fn student(name string, age int) (string, int) {
return name, age
}
name1, age1 := student("Tom", 15)
println(name1)
println(age1)
```
Output
```
Tom, 15
```
## High Order Functions
Functions in V can also take in another function as a parameter which is usually
needed for something like sort, map, filter, etc.
```go
fn square(num int) int {
return num * num
}
fn run(value int, op fn(int) int) int {
return op(value)
}
println(run(10, square))
```
Output
```
100
```
## Exercises
1. Write a V program to find the square of any number using the function.
2. Write a V program to check a given number is even or odd using the function.
3. Write a V program to convert decimal number to binary number using the function.
4. Write a V program to check whether a number is a prime number or not using the function.
5. Write a V program to get the largest element of an array using the function.
================================================
FILE: de/examples/section_3/methods.md
================================================
---
version: 1.0.0
example_title: Methods
---
# Methods
V does not have classes. But one can define methods for types.
A method is a function that has a special receiver argument,
only a receiver of the specified type can execute this function.
The receiver has its own argument list between `fn` and the method name.
```go
struct User {
name string
email string
mut:
age int
}
fn (u User) can_register() bool {
return u.age > 15
}
fn (u mut User) has_birthday() {
u.age += 1
}
fn main() {
mut bob := User {
name: 'Bob'
email: 'bob@bob.com'
age: 15
}
alice := User {
name: 'Alice'
email: 'alice@alice-mail.com'
age: 17
}
println(bob.can_register()) // false
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.
println(alice.can_register()) // true
bob.has_birthday()
println(bob.age) // 16
}
```
This code above realizes two methods for receivers `u` of type `User`.
Note that the method `has_birthday()` has a `mut` receiver, this is needed here since we want to change its data.
The convention of V is not to use receiver names like `self`, `this` or similar things but a short, preferably one letter long, name.
## Exercises
1. Create a method for the type `Person` that determines whether a person is underage or not.
2. Create a method that determines whether an `Animal` has fur or not.
================================================
FILE: de/examples/section_3/struct.md
================================================
---
version: 1.0.0
example_title: Struct
---
# Struct
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.
For people coming from [OOP](https://en.wikipedia.org/wiki/Object-oriented_programming) languages, it can be thought as `class` but with more restrictions.
```go
struct User {
name string
email string
country string
}
fn main() {
user := User {
name: "V developers"
email: "developers@vlang.io"
country: "Canada"
}
println(user.country)
}
```
> Note: Structs are allocated on the stack.
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.
```go
user := User { name: "V developers", email: "developers@vlang.io", country: "Canada" }
```
## The `&` prefix
You can allocate a struct on the heap and get a reference to it by using the `&` prefix as follows:
```go
user := &User{"V developers", "developers@vlang.io", "Canada"}
println(user.name)
```
The type of `user` is `&User`. It's a reference to `User`.
## Access modifiers
Struct fields are `private` and `immutable` by default. Their access modifiers can be changed with `pub` and `mut`.
```go
struct User {
email string
}
```
You can define them as `private mutable`.
```go
struct User {
email string
mut:
first_name string
last_name string
}
```
You can also define them as `public immmutable` (readonly).
```go
struct User {
email string
mut:
first_name string
last_name string
pub:
sin_number int
}
```
or as `public`, but `mutable` only in the parent module.
```go
struct User {
email string
mut:
first_name string
last_name string
pub:
sin_number int
pub mut:
phone int
}
```
or `public` and `mutable` both inside and outside parent module.
```go
struct User {
email string
mut:
first_name string
last_name string
pub:
sin_number int
pub mut:
phone int
pub mut mut:
address_1 string
address_2 string
city string
country string
zip string
}
```
## Exercises
1. Create a struct that stores and displays `User` information.
2. Create a `Point` struct that holds `x` and `y` field and guard them with private and public.
================================================
FILE: de/examples/section_4/README.md
================================================
# Section 4
================================================
FILE: de/examples/section_4/array-functions.md
================================================
---
version: 1.0.0
example_title: Array Functions
---
# Array Functions
## `repeat`
Syntax
```go
array.repeat(number int)
```
Makes an array with the given element number of times.
```go
foo := [1, 2].repeat(5)
println(foo)
```
Output
```
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
```
## `delete`
Syntax
```go
array.delete(ix int)
```
Deletes the element present in the array at index `ix`.
```go
mut even_numbers := [2, 4, 6, 8, 10]
even_numbers.delete(3)
println(even_numbers)
```
Output
```
[2, 4, 6, 10]
```
## `reverse`
Syntax
```go
array.reverse()
```
Reverses the array.
```go
float_num := [1.1, 1.3, 1.25, 1.4]
float_num.reverse()
```
Output
```
[1.4, 1.25, 1.3, 1.1]
```
## `clone`
Syntax
```go
array.clone()
```
Clones and returns a new array.
```go
foo := [1, 2, 4, 5, 4, 6]
foo1 := foo.clone()
println(foo1)
```
Output
```
[1, 2, 4, 5, 4, 6]
```
================================================
FILE: de/examples/section_4/files.md
================================================
---
version: 1.0.0
example_title: Files
---
# Files
A File in V is an abstraction of any file object accessible by the program and is closely associated with `os` library.
## Reading Files
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:
```go
import os
fn main() {
mut fp := flag.new_flag_parser(os.args)
generator := fp.string('generator', '', 'generator name')
method := fp.string('method', '', 'generator method name')
path := './data/$generator/$method'
if os.file_exists(path) {
print_generator_sample(path)
} else {
println('File does not exist')
return
}
}
fn print_generator_sample(path string) {
contents := os.read_file(path.trim_space()) or {
println('Failed to open $path')
return
}
lines := contents.split_into_lines()
length := lines.len
print_random_element(lines, length)
}
fn print_random_element(lines []string, length int) {
rand.seed(time.now().uni)
println(lines[rand.next(length-1)])
}
```
## Writing files
Writing files in V is similar to read files.
```go
import os
fn main() {
path := './data/file.txt'
text := 'Full text description.'
if contents := os.write_file(path, text) or {
println('Failed while creating file')
return
}
content_lines = read_file(path)
print(content_lines)
}
fn read_file(path string) {
contents := os.read_file(path.trim_space()) or {
println('Failed to open $path')
return
}
return contents.split_into_lines()
}
```
## Exercises
1. Write a V program to create a new file with content.
2. Write a V program to read 2 different files and display their content.
3. Read how the `os` library works in V and understand how you could use it.
4. Encode a nested json string and write a new file with the result.
================================================
FILE: de/examples/section_4/json.md
================================================
---
version: 1.0.0
example_title: JSON
---
# JSON
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.
JSON is completely language agnostic and that's why it's the ideal interchange format.
To read more about JSON visit: [json.org](http://json.org).
## Parsing JSON
To parse a JSON string received by another application or generated within your existing application:
```go
import json
struct Customer {
first_name string
last_name string
hometown string
}
fn main() {
customers_string := '[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro" }, { "first_name": "Don", "last_name": "Nisnoni", "hometown": "Kupang" }]'
customers := json.decode([]Customer, customers_string) or {
eprintln('Failed to parse json')
return
}
// Print the list of customers
for customer in customers {
println('$customer.first_name $customer.last_name: $customer.hometown')
}
}
```
## Generating JSON
Creating a JSON string for communication or serialization is just as simple. We decode and encode in the example below:
```go
import json
struct Customer {
first_name string
last_name string
hometown string
}
fn main() {
customer_string := '[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro"}]'
customer := json.decode([]Customer, customer_string) or {
eprintln('Failed to parse json')
return
}
encoded_json := json.encode(customer)
println(encoded_json)
}
```
## Exercises
1. Compare how you handle JSON in your favorite language and V.
2. Build an `Address` struct that contains address information.
3. Use the `Address` struct to decode and encode a string that contains JSON format.
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.
================================================
FILE: de/examples/section_4/testing.md
================================================
---
version: 1.0.0
example_title: Testing
---
# Testing
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.
## Automated tests
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.
## Tests in V
In V, all test files have to be named with the following format: `*_test.v` and the functions should start with `test_*`.
```go
// sum.v in subfolder sum
module sum
pub fn sum(a, b int) int {
return a + b
}
```
```go
// sum_test.v
import sum
fn test_sum() {
assert sum.sum(2, 3) == 5
// assert sum.sum(2, 3) == 777 // => sum_test.v:6: FAILED assertion
}
```
To execute the test, you should run `v test_sum.v`.
### Examples
1. Testing JSON structures:
```go
import json
fn test_encode_customer(){
customer := Customer{ first_name: "Vitor", last_name: "Oliveira" }
expected := '{ "first_name": "Vitor", "last_name": "Oliveira" }'
encoded_json := json.encode(customer)
assert encoded_json == expected
}
```
2. Testing files:
```go
import os
fn test_file_creation() {
file_name := './new_file.txt'
content := 'text'
os.write_file(file_name, content)
assert content.len == os.file_size(file_name)
os.rm(file_name)
}
```
================================================
FILE: docs_style_guide.md
================================================
# Documentation Style Guide
These are the guidelines for writing documentation.
## Titles
- Each page must have a single `#`-level title at the top.
- Chapters in the same page must have `##`-level titles.
- Sub-chapters need to increase the number of `#` in the title according to
their nesting depth.
- All words in the page's title must be capitalized, except for conjunctions
like "of" and "and" .
- Only the first word of a chapter title must be capitalized.
```markdown
# Arrays
...
## How to declare an array
...
## Create an empty array
...
```
## Print Width
To be easy to read when editing the markdown code, if the sentence is too long, divide it down.
The recommended column length limit is 80.
## Code Output
To create output from code, there are two rules:
- If the output is short then put it as a comment
- If the output is quite long (column) then write it in a separate section after the code section.
## Indentation
Indentation must use spaces and the tab size must be 4.
================================================
FILE: en/examples/section_1/README.md
================================================
# Section 1
================================================
FILE: en/examples/section_1/comment.md
================================================
---
version: 1.0.0
example_title: Comments
---
# Comments
V supports single line comments `//` and multi-line comments `/* */`.
They should be used for documenting the code for letting the other users know how the code works.
It can also be used for temporarily commenting the code which has to be used later on.
```v
// This is a single line comment
/* This is a
* multi-line comment
* /* This could be nested as well*/
*/
```
================================================
FILE: en/examples/section_1/hello_world.md
================================================
---
version: 1.0.0
example_title: Hello World
---
# Formatted Print
Printing is handled by various I/O stream functions. One should know where to use them accordingly.
- `print`: for printing the text to the output stream without a newline.
- `println`: same as `print` but newline appended automatically.
- `eprint`: same as `print` but the output goes to error stream (stderr).
- `eprintln`: same as `println` but the output goes to error stream (stderr).
- `panic`: outputs and exits from the program.
```v
print('Hello World')
print('Hello V')
```
This will print `Hello WorldHello V`
If you want to print the next line on a new line you would have to do `\n`.
```v
print('Hello World \n')
print('Hello V ')
```
If you don't want to use `\n` then you can use `println` instead.
## Comments
V supports single line comments `//` and multi-line comments `/* */`.
They should be used for documenting the code for letting the other users know how the code works.
It can also be used for temporarily commenting the code which has to be used later on.
```v
// This is a single line comment
/* This is a
* multi-line comment
* /* This could be nested as well*/
*/
```
## Exercises
Try uncommenting the code in `hello.v` and see what happens.
================================================
FILE: en/examples/section_1/keywords.md
================================================
---
version: 1.0.0
example_title: Keywords
---
# Keywords
V is a very small language so it has few keywords. There are around 25 keywords.
| Keywords | in | V | Programming | Language |
| -------- | ------ | --- | ----------- | --------- |
| break | const | as | continue | defer |
| else | enum | fn | for | struct |
| go | goto | if | import | return |
| type | pub | mut | in | interface |
| match | module | or | none | |
Like other languages, they cannot be used as a variable.
================================================
FILE: en/examples/section_1/primitives.md
================================================
---
version: 1.0.0
example_title: Primitives
---
# Primitives
V has less primitive types than Go.
## Basic Types
- bool either `true` or `false`
- string
- integer type `int`
- float type `float`
- rune (Unicode string)
## Compound Types
- arrays `[]`
- map `{}`
- struct
## Integer
Integer is sub-classified into `signed` and `unsigned`. `signed` means positive or negative and `unsigned` means positive only.
### Signed Integer
| Type | Size | Range |
| ------ | :------: | --------------------------------------: |
| int8 | 8 bits | -128 to 2<sup>7</sup> -1 |
| int16 | 16 bits | -2<sup>15</sup> to 2<sup>15</sup> - 1 |
| int | 32 bits | -2<sup>31</sup> to 2<sup>31</sup> - 1 |
| int64 | 64 bits | -2<sup>63</sup> to 2<sup>63</sup> - 1 |
| int128 | 128 bits | -2<sup>127</sup> to 2<sup>127</sup> - 1 |
### Unsigned Integer
| Type | Size | Range |
| ---- | :------: | -----------------------: |
| byte | 8 bits | 0 to 2<sup>7</sup> -1 |
| u16 | 16 bits | 0 to 2<sup>15</sup> - 1 |
| u32 | 32 bits | 0 to 2<sup>31</sup> - 1 |
| u64 | 64 bits | 0 to 2<sup>63</sup> - 1 |
| u128 | 128 bits | 0 to 2<sup>127</sup> - 1 |
================================================
FILE: en/examples/section_1/strings.md
================================================
---
version: 1.0.0
example_title: Strings
---
# Strings
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.
```go
name := 'Bob'
println(name) // Bob
println(name.len) // 3
```
Getting the length of a string works with `.len`.
## Interpolation
It is possible to do string interpolation with `$` in front of the variable:
```go
name := 'Bob'
println('Hello $name!') // Hello Bob!
```
One can have more complex expressions with interpolation syntax by using `${}`:
```go
struct User {
name string
age int
}
bob := User {
name: 'Bob'
age: 17
}
println('Say Hello to a new User: ${bob.name}, ${bob.age}') // Say Hello to new User: Bob, 17
println('${bob.name}s age is higher or equal to 18: ${bob.age >= 18}') // 0 <=> number representation for false
```
## Concatenation
Strings can be concatenated with the `+` operator.
```go
text := 'Hello'
concatenated_text := text + ' World!'
println(text) // Hello
println(text + ' World!') // Hello World!
println(concatenated_text) // Hello World!
```
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`.
```go
mut hello := 'Hello '
hello += 'from V!' // appends 'from V!' to the string stored in hello.
println(hello) // Hello from V!
```
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.
```go
robert := 'Robert'
bert := robert[2..robert.len] // bert
rob := robert[0..3] // Rob
println('The persons of interest are: $robert, $bert, $rob') // The persons of interest are: Robert, bert, Rob
```
### Notes
When using `some_string[start..end]` syntax the `end` is **not** inclusive.
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`:
```go
age := 25
println('age = ' + age)
```
We therefore need to convert it to string by using `.str()` or use string interpolation (preferred):
```go
age := 25
println('age = ' + age.str()) // age = 25
println('age = $age') // age = 25
```
To define character literals use: ` `` `. Raw strings can be defined as prepending `r`. They are not escaped.
```go
hello := 'Hello\nWorld'
println(hello) // Hello
// World
raw_hello := r'Hello\nWorld'
println(raw_hello) // Hello\nWorld
```
================================================
FILE: en/examples/section_1/variables.md
================================================
---
version: 1.0.0
example_title: Variables
---
# Variables
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.
```go
age := 23 // int
name := 'Alice' // string
is_adult := age > 21 // bool
println(age_str) // 23
println(name) // Alice
println(is_adult) // true
```
> Note: Variables can only be defined in a function. There are no global variables and no global state in V.
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 `=`.
```go
mut age := 20 // declare the mutable variable age and assign it to the value 20.
println(age) // 20
age = 21 // assign a new value to age
println(age) // 21
```
Leaving out the `mut` keyword here would result in an error because the value of an immutable variable cannot be changed.
```go
fn main() {
age = 20
println(age)
}
```
The code above would result in an error during compilation because the variable `age` is not declared,
```go
fn main() {
mut age := 20 // we declare the mutable variable age and assign it to the value 20.
println(age) // 20
age := 21 // ERROR
}
```
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 `=`.
Like Go, You can also use `_` for ignoring values when it is not needed. Usually used in multi return functions.
```go
_ := "I don't need this value"
println(_) // ERROR: Cannot use `_` as value
```
## Naming Rules
The following are the rules which should be kept in mind while naming variables.
- Name should not contain Uppercase letters like `AlphaTest`
- Use underscores as separators like `hello_world`
- Name should be descriptive as possible
- Name should not contain `__`
- Name should not contain any space
- If the name is longer than 11 then it must use `_` as separator
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.
### Valid Names
```go
boby
john_dads
myfamily_number
```
### Invalid Names
```go
IamNotValid
new Make
```
================================================
FILE: en/examples/section_2/README.md
================================================
# Section 2
================================================
FILE: en/examples/section_2/if-else.md
================================================
---
version: 1.0.0
example_title: If statement
---
# If statement
## The `if` statement
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:
```go
john_height := 100
maria_height := 178
if john_height < maria_height {
println("Maria is taller than John")
}
```
In the above code, `println()` will only execute when the condition is true.
There are no parentheses needed for surrounding the condition, and the braces are always required.
## The `else` statement
An `else` statement is a programming conditional statement in which when `if` evaluates to false then the code in `else` block executes.
```go
joey_age := 12
kevin_age := 15
if joey_age > kevin_age {
println("Joey is older")
} else {
println("Kevin is older")
}
```
In this example, the code inside the `else` block will execute because the condition in `if` evaluates to `false`.
## The `else if` statement
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.
```go
tom_age := 20
ashia_age := 38
if tom_age < ashia_age {
println("Tom is younger than Ashia")
} else if tom_age > ashia_age {
println("Tom is older than Ashia")
} else {
println("Tom and Ashia are the same age")
}
```
Output
```console
Tom is younger than Asia
```
## Nested `if..else` statement
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.
```go
tom_age := 20
ashia_age := 38
if tom_age < ashia_age {
if tom_age < 18 {
println("tom_age < 18 and younger than Ashia.")
} else {
println("tom_age >= 18 and younger than Ashia.")
}
} else if tom_age > ashia_age {
println("$tom_age > $ashia_age")
} else {
println("$tom_age == $ashia_age")
}
```
Output
```console
tom_age >= 18 and younger than Ashia.
```
## Using `if..else` as expression
The `if..else` can also be used as an expression:
```go
tom_age := 20
ashia_age := 38
s := if tom_age < ashia_age {
"Tom is the youngest"
} else {
"Ashia is the youngest"
}
print(s)
```
Output
```console
Tom is the youngest
```
## Exercises
1. Write a V program to accept two integers and check whether they are equal or not.
2. Write a V program to check whether a given number is even or odd.
3. Write a V program to check whether a given number is positive or negative.
4. Write a V program to find whether a given year is a leap year or not.
================================================
FILE: en/examples/section_2/loops.md
================================================
---
version: 1.0.0
example_title: Loops
---
# Looping Constructs
There's only one type of loop in V language, like Go which can be used in many ways.
## `for` loop
`for` loops offer a quick and easy way to do something repeatedly.
They're handy, if you want to run the same code over and over again, each time with a different value.
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;
for example, the idea "Go five steps to the east" could be expressed this way as a loop:
```go
for i := 0; i < 5; i++ {
println('Walking one step')
}
```
V has the `for` looping construct and the loop can be written in different ways:
- `in` operator for array/map
```go
ages := [18, 25, 32, 43, 50]
for age in ages {
println(age)
}
```
> Note: The value is read-only.
- `for` loop with a condition
This is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.
There are no parentheses surrounding the condition, and the braces are always required.
```go
mut factorial := 1
mut counter := 1
for {
counter++
if counter > 5 {
println(factorial)
break
}
factorial = factorial * counter
}
println(counter)
```
Output
```console
120
6
```
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.
```go
mut factorial := 1
mut counter := 1
for counter <= 5 {
factorial = factorial * counter
counter++
}
println(factorial)
println(counter)
```
Output
```console
120
6
```
- Traditional C style
```go
mut factorial := 1
mut counter := 1
for counter = 1; counter < 6; counter++ {
factorial = factorial * counter
if counter == 5 {
print(factorial)
continue
}
println(counter)
}
```
- Infinite Loop
`for` loop can also be infinite
```go
for {
println('foo')
}
```
## Exercises
1. Write a V program to display the first 10 natural numbers.
2. Write a V program to find the sum of first 10 natural numbers.
3. Write a V program to print the integers inside an array and also print their mean.
4. Write a V program to read 10 numbers from keyboard and find their sum and average.
5. Write a V program to display the cube of the number upto given an integer.
================================================
FILE: en/examples/section_2/match.md
================================================
---
version: 1.0.0
example_title: Match
---
# Match
## The `match` statement
A match statement is a short-hand way for `if - else`.
If the input is matched the statement block of the first matching branch will be executed and its last expression will be returned.
The `else` branch will be executed when there is no other matching branch.
```v
num := 1
match num % 2 == 0 {
true { print('The input number is even.') }
else { print('The input number is odd.') }
}
```
One can also initialize variables using `match` to have different values according to a condition.
```v
num := 3
s := match num {
1 { 'one' }
2 { 'two' }
else {
'many'
}
}
```
Examples:
```v
fn even(num int) bool {
match num % 2 == 0 {
true { print('The input number is even.') }
else { print('The input number is odd.') }
}
}
fn num_to_str(num int) int {
match num {
1 { 'one' }
2 { 'two' }
else {
'many'
}
}
}
fn main() {
println(even(14)) // 'The input number is even.'
println(even(3)) // 'The input number is odd.'
println(num_to_str(1)) // 'one'
println(num_to_str(2)) // 'two'
println(num_to_str(352)) // 'many'
}
```
### Enums
One can also match on `enum` values (variants) as branches by using the `.variant_here` syntax:
```v
enum Animal {
cat
dog
goldfish
pig
}
fn makes_miau(a Animal) bool {
return match a {
.cat { true }
else { false }
}
}
fn is_land_creature(a Animal) bool {
return match a {
.cat { true }
.dog { true }
.pig { true }
else {
false
}
}
}
// OR LIKE THAT
fn is_land_creature_alt(a Animal) bool {
return match a {
.goldfish { false }
else {
true
}
}
}
fn main() {
my_cat := Animal.cat
my_goldfish := Animal.goldfish
println(makes_miau(my_cat)) // true
println(is_land_creature(my_cat)) // true
println(is_land_creature(my_goldfish)) // false
}
```
### Exercises
1. Write a V program that creates an array of all even numbers from 1 to 50.
2. Write a V program that, given an array of numbers, returns the maximum value.
3. Write a V program that determines whether color (enum) is red or blue
================================================
FILE: en/examples/section_2/operator.md
================================================
---
version: 1.0.0
example_title: Operators
---
# Operators
V supports the following operators:
## Basic Operators
- `+` (addition) for int, float and string
- `-` (subtraction) for int and float
- `*` (multiplication) for int and float
- `/` (division) for int and float
- `%` (modulos) for int
- `=` (assignment) for changing values
- `:=` for initialising values
```v
println(3 + 5)
println(2.0 + 5.0)
println('hello' + 'world')
println(9 - 10)
println(7.0 - 5.0)
println(3 * 5)
println(2.0 * 4)
println(23 / 3)
println(25.0 / 5.0)
println(27 % 5)
println(27 % 3)
```
Output
```v
8
7.0
hello world
-1
2.0
15
8.0
7
5.0
2
0
```
> Note: Unlike other languages, V doesn't allow modulus with float.
## Comparison Operators
- `>` greater than
- `<` lesser than
- `==` equal to
- `>=` greater than or equal to
- `<=` lesser than or equal to
- `!=` not equal to
## Boolean Operators
- `&&` and
- `||` or
- `!` not
## Bitwise Operators
- `<<` left bitshift
- `>>` right bitshift
- `&` bitwise and
- `|` bitwise or
- `^` bitwise xor
## Assignments Operators
- `+=` same as `foo = foo + var`
- `-=` same as `foo = foo - var`
- `*=` same as `foo = foo * var`
- `/=` same as `foo = foo / var`
- `&=` same as `foo = foo & var`
- `|=` same as `foo = foo | var`
- `>>=` same as `foo = foo >> var`
- `<<=` same as `foo = foo << var`
## Special Operators
- `in` for membership
- `none` for optional
================================================
FILE: en/examples/section_3/README.md
================================================
# Section 3
================================================
FILE: en/examples/section_3/arrays.md
================================================
---
version: 1.0.0
example_title: Arrays
---
# Arrays
An array is a collection of items stored in contiguous memory locations. It's an aggregate data structure that is designed to store a group of objects of the same type. It's the most efficient data structure for storing and accessing a sequence of objects.
## How to declare an array
**Create an array that holds integer values:**
```go
mut ages := [18, 25, 37]
println(ages)
```
Output
```console
[18, 25, 37]
```
**Or create an array that holds string values:**
```go
mut users := ['vbrazo', 'donnisnoni95', 'Delta456']
println(users)
```
Output
```
['vbrazo', 'donnisnoni95', 'Delta456']
```
> Note: All elements must have the same type. The following code will not compile.
```go
mut users := ['vbrazo', 'donnisnoni95', 'Delta456', 0]
```
Output
```
~/main.v:2:43: bad array element type `int` instead of `string`
```
## Create an empty array
If you want to create a new empty array, just declare `[]` followed by the data type.
```go
mut names := []string
mut numbers := []int
```
## Accessing element of the array
```go
mut users := ['vbrazo', 'donnisnoni95', 'Delta456']
println(users[0])
println(users[2])
println(users[1])
```
Output
```go
vbrazo
Delta456
donnisnoni95
```
## Append a value to an array
`<<` is an operator that appends a value to the end of the array.
```go
mut ages := [18]
ages << 47
println(ages)
```
Output
```go
[18, 47]
```
It can also append an entire array.
```go
mut ages := [18]
ages << [47, 49]
println(ages)
```
Output
```
[18, 47, 49]
```
## Length/size of an array
`.len` method returns the length of the array.
```go
mut names := ['Thiago', 'John']
println(names.len)
```
Output
```
2
```
## In operator
`in` check if an element is inside an array.
```go
mut names := ['Thiago', 'Alex', 'Joe']
println('Vitor' in names)
println('Thiago' in names)
```
Output
```
false
true
```
## Slicing an array
It's easy to slice an array in V. You can slice an array with the default
V slicing feature without having to call the `slice ()` method.
The syntax is like this `my_array[start..end]`
```go
animals := ['lion', 'goose', 'chicken', 'turkey', 'tiger']
poultry := animals[1..4]
println(poultry) // ["goose", "chicken", "turkey"]
```
If you want to slice from the start of the index, just ignore it to put `0` and using instead `my_array[..end]` or `my_array[start..]`.
```go
x := ['h', 'e', 'l', 'l', 'o']
y := x[..x.len-1]
z := x[1..]
println(y) // ['h', 'e', 'l', 'l']
println(z) // ['e', 'l', 'l', '0']
```
## Exercises
1. Write a V program to store elements in an array and print it.
2. Write a V program to read n number of values in an array and display it in reverse order.
3. Write a V program to find the sum of all elements of the array.
4. Write a V program to copy the elements of one array into another array.
5. Write a V program to count a total number of duplicate elements in an array.
================================================
FILE: en/examples/section_3/functions.md
================================================
---
version: 1.0.0
example_title: Functions
---
# Functions
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.
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
for a single part of the functionality provided by the software to keep your code maintainable.
Like C and Go, functions cannot be overloaded.
```go
fn sum(x, y int) int {
return x + y
}
println(sum(77, 33)) // 110
```
> Note: The type comes after the argument's name.
```go
fn full_name(first_name, last_name string) string {
return first_name + ' ' + last_name
}
println(full_name("Vitor", "Oliveira")) // Vitor Oliveira
```
## Variadic Functions
Functions can also be variadic i.e. accept an infinite number of arguments.
They are not arrays and cannot be returned.
```go
fn foo(test ...string) {
for txt in test {
println(txt)
}
}
foo("V", "is", "the", "best", "lang" , "ever")
```
Output
```console
V
is
the
best
lang
ever
```
## Multi-Return Functions
Similar to Go, functions in V can also return multiple and with a different type.
```go
fn student(name string, age int) (string, int) {
return name, age
}
name, age := student("Tom", 15)
println(name1)
println(age1)
```
Output
```console
Tom, 15
```
## High Order Functions
Functions in V can also take in another function as a parameter which is usually
needed for something like sort, map, filter, etc.
```go
fn square(num int) int {
return num * num
}
fn run(value int, op fn(int) int) int {
return op(value)
}
println(run(10, square)) // 100
```
## Naming Rules
The following are the rules which should be kept in mind while naming functions.
- Name should not contain Uppercase letters like `AlphaTest`
- Use underscores as separators like `hello_world`
- Name should not start with `_`
- Name should be descriptive as possible
- Name should not contain `__`
- Name should not contain any space
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.
### Valid Names
```go
fn i_am_valid()
fn thisworkstoo()
fn print_values_through_struct()
```
### Invalid Names
```go
fn IamNotValid()
fn _print()
fn print__logs()
fn new Make Lexer()
```
## Exercises
1. Write a V program to find the square of any number using the function.
2. Write a V program to check a given number is even or odd using the function.
3. Write a V program to convert decimal number to binary number using the function.
4. Write a V program to check whether a number is a prime number or not using the function.
5. Write a V program to get the largest element of an array using the function.
================================================
FILE: en/examples/section_3/methods.md
================================================
---
version: 1.0.0
example_title: Methods
---
# Methods
V does not have classes. But one can define methods for types.
A method is a function that has a special receiver argument,
only a receiver of the specified type can execute this function.
The receiver has its own argument list between `fn` and the method name.
```go
struct User {
name string
email string
mut:
age int
}
fn (u User) can_register() bool {
return u.age > 15
}
fn (u mut User) has_birthday() {
u.age += 1
}
fn main() {
mut bob := User {
name: 'Bob'
email: 'bob@bob.com'
age: 15
}
alice := User {
name: 'Alice'
email: 'alice@alice-mail.com'
age: 17
}
println(bob.can_register())
println("Bob needs to be 16 to register, but he only is ${bob.age}.")
println(alice.can_register())
bob.has_birthday()
println(bob.age)
}
```
Output
```console
false
Bob needs to be 16 to register, but he only is 15.
true
16
```
This code above realizes two methods for receivers `u` of type `User`.
Note that the method `has_birthday()` has a `mut` receiver, this is needed here since we want to change its data.
The convention of V is not to use receiver names like `self`, `this` or similar things but a short, preferably one letter long, name.
## Exercises
1. Create a method for the type `Person` that determines whether a person is underage or not.
2. Create a method that determines whether an `Animal` has fur or not.
================================================
FILE: en/examples/section_3/struct.md
================================================
---
version: 1.0.0
example_title: Struct
---
# Struct
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.
For people coming from [OOP](https://en.wikipedia.org/wiki/Object-oriented_programming) languages, it can be thought as `class` but with more restrictions.
```go
struct User {
name string
email string
country string
}
fn main() {
user := User {
name: "V developers"
email: "developers@vlang.io"
country: "Canada"
}
println(user.country)
}
```
> Note: Structs are allocated on the stack.
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.
```go
user := User { name: "V developers", email: "developers@vlang.io", country: "Canada" }
```
## The `&` prefix
You can also allocate a struct on the heap and get a reference to it by using the `&` prefix as follows:
```go
user := &User{"V developers", "developers@vlang.io", "Canada"}
println(user.name)
```
The type of `user` is `&User`. It's a reference to `User`.
## Access modifiers
Struct fields are `private` and `immutable` by default. Their access modifiers can be changed with `pub` and `mut`.
```go
struct User {
email string // private and immutable (default)
}
```
You can define them as `private mutable`.
```go
struct User {
email string
mut:
first_name string // private mutable
last_name string // (you can list multiple fields with the same access modifier)
}
```
You can also define them as `public immmutable` (readonly).
```go
struct User {
email string
mut:
first_name string
last_name string
pub:
sin_number int // public immutable (readonly)
}
```
or as `public`, but `mutable` only in the parent module.
```go
struct User {
email string
mut:
first_name string
last_name string
pub:
sin_number int
pub mut:
phone int // public, but mutable only in parent module
}
```
or `public` and `mutable` both inside and outside parent module.
```go
struct User {
email string
mut:
first_name string
last_name string
pub:
sin_number int
pub mut:
phone int
__global:
address_1 string // public and mutable both inside and outside parent module
address_2 string // (not recommended to use, that's why the 'global' keyword
city string // starts with __)
country string
zip string
}
```
## Naming Rules
- The name of the `struct` should always be capital.
- Use [`Snake_Case`](https://github.com/v-community/v_by_example/blob/master/en/examples/section_1/variables.md#naming-rules) for variable naming.
## Exercises
1. Create a struct that stores and displays `User` information.
2. Create a `Point` struct that holds `x` and `y` field and guard them with private and public.
================================================
FILE: en/examples/section_4/README.md
================================================
# Section 4
================================================
FILE: en/examples/section_4/array-functions.md
================================================
---
version: 1.0.0
example_title: Array Functions
---
# Array Functions
## `repeat`
Syntax
```go
array.repeat(number type)
```
Makes an array with the given element number of times.
```go
foo := [1, 2].repeat(5)
println(foo) // [1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
```
## `delete`
Syntax
```go
array.delete(ix type)
```
Deletes the element present in the array at index `ix`.
```go
mut even_numbers := [2, 4, 6, 8, 10]
even_numbers.delete(3)
println(even_numbers) // [2, 4, 6, 10]
```
## `reverse`
Syntax
```go
array.reverse()
```
Reverses the array.
```go
float_num := [1.1, 1.3, 1.25, 1.4]
float_num.reverse() // [1.4, 1.25, 1.3, 1.1]
```
## `clone`
Syntax
```go
array.clone()
```
Clones and returns a new array.
```go
foo := [1, 2, 4, 5, 4, 6]
foo1 := foo.clone()
println(foo1) // [1, 2, 4, 5, 4, 6]
```
================================================
FILE: en/examples/section_4/files.md
================================================
---
version: 1.0.0
example_title: Files
---
# Files
A File in V is an abstraction of any file object accessible by the program and is closely associated with `os` library.
## Reading Files
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:
```go
import os
fn main() {
mut fp := flag.new_flag_parser(os.args)
generator := fp.string('generator', '', 'generator name')
method := fp.string('method', '', 'generator method name')
path := './data/$generator/$method'
if os.file_exists(path) {
print_generator_sample(path)
} else {
println('File does not exist')
return
}
}
fn print_generator_sample(path string) {
contents := os.read_file(path.trim_space()) or {
println('Failed to open $path')
return
}
lines := contents.split_into_lines()
length := lines.len
print_random_element(lines, length)
}
fn print_random_element(lines []string, length int) {
rand.seed(time.now().uni)
println(lines[rand.next(length-1)])
}
```
## Writing files
Writing files in V is similar to read files.
```go
import os
fn main() {
path := './data/file.txt'
text := 'Full text description.'
if contents := os.write_file(path, text) or {
println('Failed while creating file')
return
}
content_lines = read_file(path)
print(content_lines)
}
fn read_file(path string) {
contents := os.read_file(path.trim_space()) or {
println('Failed to open $path')
return
}
return contents.split_into_lines()
}
```
## Exercises
1. Write a V program to create a new file with content.
2. Write a V program to read 2 different files and display their content.
3. Read how the `os` library works in V and understand how you could use it.
4. Encode a nested json string and write a new file with the result.
================================================
FILE: en/examples/section_4/json.md
================================================
---
version: 1.0.0
example_title: JSON
---
# JSON
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.
JSON is completely language agnostic and that's why it's the ideal interchange format.
To read more about JSON visit: [json.org](http://json.org).
## Parsing JSON
To parse a JSON string received by another application or generated within your existing application:
```go
import json
struct Customer {
first_name string
last_name string
hometown string
}
fn main() {
customers_string := '[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro" }, { "first_name": "Don", "last_name": "Nisnoni", "hometown": "Kupang" }]'
customers := json.decode([]Customer, customers_string) or {
eprintln('Failed to parse json')
return
}
// Print the list of customers
for customer in customers {
println('$customer.first_name $customer.last_name: $customer.hometown')
}
}
```
## Generating JSON
Creating a JSON string for communication or serialization is just as simple. We decode and encode in the example below:
```go
import json
struct Customer {
first_name string
last_name string
hometown string
}
fn main() {
customer_string := '[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro"}]'
customer := json.decode([]Customer, customer_string) or {
eprintln('Failed to parse json')
return
}
encoded_json := json.encode(customer)
println(encoded_json)
}
```
## Exercises
1. Compare how you handle JSON in your favorite language and V.
2. Build an `Address` struct that contains address information.
3. Use the `Address` struct to decode and encode a string that contains JSON format.
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.
================================================
FILE: en/examples/section_4/testing.md
================================================
---
version: 1.0.0
example_title: Testing
---
# Testing
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.
## Automated tests
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.
## Tests in V
In V, all test files have to be named with the following format: `*_test.v` and the functions should start with `test_*`.
```go
// sum.v in subfolder sum
module sum
pub fn sum(a, b int) int {
return a + b
}
```
```go
// sum_test.v
import sum
fn test_sum() {
assert sum.sum(2, 3) == 5
// assert sum.sum(2, 3) == 777 // => sum_test.v:6: FAILED assertion
}
```
To execute the test, you should run `v test_sum.v`.
### Examples
1. Testing JSON structures:
```go
import json
fn test_encode_customer(){
customer := Customer{ first_name: "Vitor", last_name: "Oliveira" }
expected := '{ "first_name": "Vitor", "last_name": "Oliveira" }'
encoded_json := json.encode(customer)
assert encoded_json == expected
}
```
2. Testing files:
```go
import os
fn test_file_creation() {
file_name := './new_file.txt'
content := 'text'
os.write_file(file_name, content)
assert content.len == os.file_size(file_name)
os.rm(file_name)
}
```
================================================
FILE: fr/section_1/Beinvenue_monde.md
================================================
---
version: 1.0.0
titre de l'example: Hello World
---
# imprimé formaté
L'impression est assurée par diverses fonctions de flux I/O. Il convient de savoir où les utiliser en conséquence.
- `print`: pour l'impression du texte dans le flux de sortie sans nouvelle ligne.
- `println`: la même que `print` mais nouvelle ligne ajoutée automatiquement.
- `eprint`: la même que `print` mais le résultat est transmis au flux d'erreurs (stderr).
- `eprintln`: la même que `println` mais le résultat est transmis au flux d'erreurs (stderr).
- `panic`: fait une production et sort du programme.
```v
print('Hello World')
print('Hello V')
```
Il sera imprimé ce qui suit `Hello WorldHello V`
Si vous souhaitez imprimer la ligne suivante sur une nouvelle ligne, vous devrez faire `\n`.
```v
print('Hello World \n')
print('Hello V ')
```
si vous ne voulez pas utiliser `\n` alors vous utilisez `println` au lieu de cela.
## Les commentaires
V soutient les commentaires d'une seule ligne `//` et les commentaires de plusieurs lignes `/* */`.
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.
```v
// Ceci est un commentaire d'une seule ligne
/* Ceci est un
* commentaire de plusiers lignes
* /* Elle peut également être imbriquée*/
*/
```
## Exercises
Essayez de décommenter le code en `hello.v` et voyez ce qui se passe.
================================================
FILE: fr/section_1/README.md
================================================
# Section 1
================================================
FILE: fr/section_1/les_chaînes de caractères.md
================================================
---
version: 1.0.0
example_title: Strings
---
# Strings
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.
```go
name := 'Bob'
println(name) // Bob
println(name.len) // 3
```
Getting the length of a string works with `.len`.
## Interpolation
It is possible to do string interpolation with `$` in front of the variable:
```go
name := 'Bob'
println('Hello $name!') // Hello Bob!
```
One can have more complex expressions with interpolation syntax by using `${}`:
```go
struct User {
name string
age int
}
bob := User {
name: 'Bob'
age: 17
}
println('Say Hello to a new User: ${bob.name}, ${bob.age}') // Say Hello to new User: Bob, 17
println('${bob.name}s age is higher or equal to 18: ${bob.age >= 18}') // 0 <=> number representation for false
```
## Concatenation
Strings can be concatenated with the `+` operator.
```go
text := 'Hello'
concatenated_text := text + ' World!'
println(text) // Hello
println(text + ' World!') // Hello World!
println(concatenated_text) // Hello World!
```
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`.
```go
mut hello := 'Hello '
hello += 'from V!' // appends 'from V!' to the string stored in hello.
println(hello) // Hello from V!
```
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.
```go
robert := 'Robert'
bert := robert[2..robert.len] // bert
rob := robert[0..3] // Rob
println('The persons of interest are: $robert, $bert, $rob') // The persons of interest are: Robert, bert, Rob
```
### Notes
When using `some_string[start..end]` syntax the `end` is **not** inclusive.
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`:
```go
age := 25
println('age = ' + age)
```
We therefore need to convert it to string by using `.str()` or use string interpolation (preferred):
```go
age := 25
println('age = ' + age.str()) // age = 25
println('age = $age') // age = 25
```
To define character literals use: ` `` `. Raw strings can be defined as prepending `r`. They are not escaped.
```go
hello := 'Hello\nWorld'
println(hello) // Hello
// World
raw_hello := r'Hello\nWorld'
println(raw_hello) // Hello\nWorld
```
================================================
FILE: fr/section_1/les_commentaires.md
================================================
---
version: 1.0.0
example_title: Comments
---
# Comments
V supports single line comments `//` and multi-line comments `/* */`.
They should be used for documenting the code for letting the other users know how the code works.
It can also be used for temporarily commenting the code which has to be used later on.
```v
// This is a single line comment
/* This is a
* multi-line comment
* /* This could be nested as well*/
*/
```
================================================
FILE: fr/section_1/les_mots_clés.md
================================================
---
version: 1.0.0
example_title: Keywords
---
# Keywords
V is a very small language so it has few keywords. There are around 25 keywords.
| Keywords | in | V | Programming | Language |
| -------- | ------ | --- | ----------- | --------- |
| break | const | as | continue | defer |
| else | enum | fn | for | struct |
| go | goto | if | import | return |
| type | pub | mut | in | interface |
| match | module | or | none | |
Like other languages, they cannot be used as a variable.
================================================
FILE: fr/section_1/les_primitives.md
================================================
---
version: 1.0.0
example_title: Primitives
---
# Primitives
V has less primitive types than Go.
## Basic Types
- bool either `true` or `false`
- string
- integer type `int`
- float type `float`
- rune (Unicode string)
## Compound Types
- arrays `[]`
- map `{}`
- struct
## Integer
Integer is sub-classified into `signed` and `unsigned`. `signed` means positive or negative and `unsigned` means positive only.
### Signed Integer
| Type | Size | Range |
| ------ | :------: | --------------------------------------: |
| int8 | 8 bits | -128 to 2<sup>7</sup> -1 |
| int16 | 16 bits | -2<sup>15</sup> to 2<sup>15</sup> - 1 |
| int | 32 bits | -2<sup>31</sup> to 2<sup>31</sup> - 1 |
| int64 | 64 bits | -2<sup>63</sup> to 2<sup>63</sup> - 1 |
| int128 | 128 bits | -2<sup>127</sup> to 2<sup>127</sup> - 1 |
### Unsigned Integer
| Type | Size | Range |
| ---- | :------: | -----------------------: |
| byte | 8 bits | 0 to 2<sup>7</sup> -1 |
| u16 | 16 bits | 0 to 2<sup>15</sup> - 1 |
| u32 | 32 bits | 0 to 2<sup>31</sup> - 1 |
| u64 | 64 bits | 0 to 2<sup>63</sup> - 1 |
| u128 | 128 bits | 0 to 2<sup>127</sup> - 1 |
================================================
FILE: fr/section_1/les_variables.md
================================================
---
version: 1.0.0
example_title: Variables
---
# Variables
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.
```go
age := 23 // int
name := 'Alice' // string
is_adult := age > 21 // bool
println(age_str) // 23
println(name) // Alice
println(is_adult) // true
```
> Note: Variables can only be defined in a function. There are no global variables and no global state in V.
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 `=`.
```go
mut age := 20 // declare the mutable variable age and assign it to the value 20.
println(age) // 20
age = 21 // assign a new value to age
println(age) // 21
```
Leaving out the `mut` keyword here would result in an error because the value of an immutable variable cannot be changed.
```go
fn main() {
age = 20
println(age)
}
```
The code above would result in an error during compilation because the variable `age` is not declared,
```go
fn main() {
mut age := 20 // we declare the mutable variable age and assign it to the value 20.
println(age) // 20
age := 21 // ERROR
}
```
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 `=`.
Like Go, You can also use `_` for ignoring values when it is not needed. Usually used in multi return functions.
```go
_ := "I don't need this value"
println(_) // ERROR: Cannot use `_` as value
```
## Naming Rules
The following are the rules which should be kept in mind while naming variables.
- Name should not contain Uppercase letters like `AlphaTest`
- Use underscores as separators like `hello_world`
- Name should be descriptive as possible
- Name should not contain `__`
- Name should not contain any space
- If the name is longer than 11 then it must use `_` as separator
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.
### Valid Names
```go
boby
john_dads
myfamily_number
```
### Invalid Names
```go
IamNotValid
new Make
```
================================================
FILE: fr/section_2/README.md
================================================
# Section 2
================================================
FILE: fr/section_2/if-else.md
================================================
---
version: 1.0.0
example_title: If statement
---
# If statement
## The `if` statement
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:
```go
john_height := 100
maria_height := 178
if john_height < maria_height {
println("Maria is taller than John")
}
```
In the above code, `println()` will only execute when the condition is true.
There are no parentheses needed for surrounding the condition, and the braces are always required.
## The `else` statement
An `else` statement is a programming conditional statement in which when `if` evaluates to false then the code in `else` block executes.
```go
joey_age := 12
kevin_age := 15
if joey_age > kevin_age {
println("Joey is older")
} else {
println("Kevin is older")
}
```
In this example, the code inside the `else` block will execute because the condition in `if` evaluates to `false`.
## The `else if` statement
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.
```go
tom_age := 20
ashia_age := 38
if tom_age < ashia_age {
println("Tom is younger than Ashia")
} else if tom_age > ashia_age {
println("Tom is older than Ashia")
} else {
println("Tom and Ashia are the same age")
}
```
Output
```console
Tom is younger than Asia
```
## Nested `if..else` statement
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.
```go
tom_age := 20
ashia_age := 38
if tom_age < ashia_age {
if tom_age < 18 {
println("tom_age < 18 and younger than Ashia.")
} else {
println("tom_age >= 18 and younger than Ashia.")
}
} else if tom_age > ashia_age {
println("$tom_age > $ashia_age")
} else {
println("$tom_age == $ashia_age")
}
```
Output
```console
tom_age >= 18 and younger than Ashia.
```
## Using `if..else` as expression
The `if..else` can also be used as an expression:
```go
tom_age := 20
ashia_age := 38
s := if tom_age < ashia_age {
"Tom is the youngest"
} else {
"Ashia is the youngest"
}
print(s)
```
Output
```console
Tom is the youngest
```
## Exercises
1. Write a V program to accept two integers and check whether they are equal or not.
2. Write a V program to check whether a given number is even or odd.
3. Write a V program to check whether a given number is positive or negative.
4. Write a V program to find whether a given year is a leap year or not.
================================================
FILE: fr/section_2/loops.md
================================================
---
version: 1.0.0
example_title: Loops
---
# Looping Constructs
There's only one type of loop in V language, like Go which can be used in many ways.
## `for` loop
`for` loops offer a quick and easy way to do something repeatedly.
They're handy, if you want to run the same code over and over again, each time with a different value.
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;
for example, the idea "Go five steps to the east" could be expressed this way as a loop:
```go
for i := 0; i < 5; i++ {
println('Walking one step')
}
```
V has the `for` looping construct and the loop can be written in different ways:
- `in` operator for array/map
```go
ages := [18, 25, 32, 43, 50]
for age in ages {
println(age)
}
```
> Note: The value is read-only.
- `for` loop with a condition
This is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.
There are no parentheses surrounding the condition, and the braces are always required.
```go
mut factorial := 1
mut counter := 1
for {
counter++
if counter > 5 {
println(factorial)
break
}
factorial = factorial * counter
}
println(counter)
```
Output
```console
120
6
```
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.
```go
mut factorial := 1
mut counter := 1
for counter <= 5 {
factorial = factorial * counter
counter++
}
println(factorial)
println(counter)
```
Output
```console
120
6
```
- Traditional C style
```go
mut factorial := 1
mut counter := 1
for counter = 1; counter < 6; counter++ {
factorial = factorial * counter
if counter == 5 {
print(factorial)
continue
}
println(counter)
}
```
- Infinite Loop
`for` loop can also be infinite
```go
for {
println('foo')
}
```
## Exercises
1. Write a V program to display the first 10 natural numbers.
2. Write a V program to find the sum of first 10 natural numbers.
3. Write a V program to print the integers inside an array and also print their mean.
4. Write a V program to read 10 numbers from keyboard and find their sum and average.
5. Write a V program to display the cube of the number upto given an integer.
================================================
FILE: fr/section_2/match.md
================================================
---
version: 1.0.0
example_title: Match
---
# Match
## The `match` statement
A match statement is a short-hand way for `if - else`.
If the input is matched the statement block of the first matching branch will be executed and its last expression will be returned.
The `else` branch will be executed when there is no other matching branch.
```v
num := 1
match num % 2 == 0 {
true { print('The input number is even.') }
else { print('The input number is odd.') }
}
```
One can also initialize variables using `match` to have different values according to a condition.
```v
num := 3
s := match num {
1 { 'one' }
2 { 'two' }
else {
'many'
}
}
```
Examples:
```v
fn even(num int) bool {
match num % 2 == 0 {
true { print('The input number is even.') }
else { print('The input number is odd.') }
}
}
fn num_to_str(num int) int {
match num {
1 { 'one' }
2 { 'two' }
else {
'many'
}
}
}
fn main() {
println(even(14)) // 'The input number is even.'
println(even(3)) // 'The input number is odd.'
println(num_to_str(1)) // 'one'
println(num_to_str(2)) // 'two'
println(num_to_str(352)) // 'many'
}
```
### Enums
One can also match on `enum` values (variants) as branches by using the `.variant_here` syntax:
```v
enum Animal {
cat
dog
goldfish
pig
}
fn makes_miau(a Animal) bool {
return match a {
.cat { true }
else { false }
}
}
fn is_land_creature(a Animal) bool {
return match a {
.cat { true }
.dog { true }
.pig { true }
else {
false
}
}
}
// OR LIKE THAT
fn is_land_creature_alt(a Animal) bool {
return match a {
.goldfish { false }
else {
true
}
}
}
fn main() {
my_cat := Animal.cat
my_goldfish := Animal.goldfish
println(makes_miau(my_cat)) // true
println(is_land_creature(my_cat)) // true
println(is_land_creature(my_goldfish)) // false
}
```
### Exercises
1. Write a V program that creates an array of all even numbers from 1 to 50.
2. Write a V program that, given an array of numbers, returns the maximum value.
3. Write a V program that determines whether color (enum) is red or blue
================================================
FILE: fr/section_2/operator.md
================================================
---
version: 1.0.0
example_title: Operators
---
# Operators
V supports the following operators:
## Basic Operators
- `+` (addition) for int, float and string
- `-` (subtraction) for int and float
- `*` (multiplication) for int and float
- `/` (division) for int and float
- `%` (modulos) for int
- `=` (assignment) for changing values
- `:=` for initialising values
```v
println(3 + 5)
println(2.0 + 5.0)
println('hello' + 'world')
println(9 - 10)
println(7.0 - 5.0)
println(3 * 5)
println(2.0 * 4)
println(23 / 3)
println(25.0 / 5.0)
println(27 % 5)
println(27 % 3)
```
Output
```v
8
7.0
hello world
-1
2.0
15
8.0
7
5.0
2
0
```
> Note: Unlike other languages, V doesn't allow modulus with float.
## Comparison Operators
- `>` greater than
- `<` lesser than
- `==` equal to
- `>=` greater than or equal to
- `<=` lesser than or equal to
- `!=` not equal to
## Boolean Operators
- `&&` and
- `||` or
- `!` not
## Bitwise Operators
- `<<` left bitshift
- `>>` right bitshift
- `&` bitwise and
- `|` bitwise or
- `^` bitwise xor
## Assignments Operators
- `+=` same as `foo = foo + var`
- `-=` same as `foo = foo - var`
- `*=` same as `foo = foo * var`
- `/=` same as `foo = foo / var`
- `&=` same as `foo = foo & var`
- `|=` same as `foo = foo | var`
- `>>=` same as `foo = foo >> var`
- `<<=` same as `foo = foo << var`
## Special Operators
- `in` for membership
- `none` for optional
================================================
FILE: fr/section_3/README.md
================================================
# Section 3
================================================
FILE: fr/section_3/arrays.md
================================================
---
version: 1.0.0
example_title: Arrays
---
# Arrays
An array is a collection of items stored in contiguous memory locations. It's an aggregate data structure that is designed to store a group of objects of the same type. It's the most efficient data structure for storing and accessing a sequence of objects.
## How to declare an array
**Create an array that holds integer values:**
```go
mut ages := [18, 25, 37]
println(ages)
```
Output
```console
[18, 25, 37]
```
**Or create an array that holds string values:**
```go
mut users := ['vbrazo', 'donnisnoni95', 'Delta456']
println(users)
```
Output
```
['vbrazo', 'donnisnoni95', 'Delta456']
```
> Note: All elements must have the same type. The following code will not compile.
```go
mut users := ['vbrazo', 'donnisnoni95', 'Delta456', 0]
```
Output
```
~/main.v:2:43: bad array element type `int` instead of `string`
```
## Create an empty array
If you want to create a new empty array, just declare `[]` followed by the data type.
```go
mut names := []string
mut numbers := []int
```
## Accessing element of the array
```go
mut users := ['vbrazo', 'donnisnoni95', 'Delta456']
println(users[0])
println(users[2])
println(users[1])
```
Output
```go
vbrazo
Delta456
donnisnoni95
```
## Append a value to an array
`<<` is an operator that appends a value to the end of the array.
```go
mut ages := [18]
ages << 47
println(ages)
```
Output
```go
[18, 47]
```
It can also append an entire array.
```go
mut ages := [18]
ages << [47, 49]
println(ages)
```
Output
```
[18, 47, 49]
```
## Length/size of an array
`.len` method returns the length of the array.
```go
mut names := ['Thiago', 'John']
println(names.len)
```
Output
```
2
```
## In operator
`in` check if an element is inside an array.
```go
mut names := ['Thiago', 'Alex', 'Joe']
println('Vitor' in names)
println('Thiago' in names)
```
Output
```
false
true
```
## Slicing an array
It's easy to slice an array in V. You can slice an array with the default
V slicing feature without having to call the `slice ()` method.
The syntax is like this `my_array[start..end]`
```go
animals := ['lion', 'goose', 'chicken', 'turkey', 'tiger']
poultry := animals[1..4]
println(poultry) // ["goose", "chicken", "turkey"]
```
If you want to slice from the start of the index, just ignore it to put `0` and using instead `my_array[..end]` or `my_array[start..]`.
```go
x := ['h', 'e', 'l', 'l', 'o']
y := x[..x.len-1]
z := x[1..]
println(y) // ['h', 'e', 'l', 'l']
println(z) // ['e', 'l', 'l', '0']
```
## Exercises
1. Write a V program to store elements in an array and print it.
2. Write a V program to read n number of values in an array and display it in reverse order.
3. Write a V program to find the sum of all elements of the array.
4. Write a V program to copy the elements of one array into another array.
5. Write a V program to count a total number of duplicate elements in an array.
================================================
FILE: fr/section_3/functions.md
================================================
---
version: 1.0.0
example_title: Functions
---
# Functions
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.
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
for a single part of the functionality provided by the software to keep your code maintainable.
Like C and Go, functions cannot be overloaded.
```go
fn sum(x, y int) int {
return x + y
}
println(sum(77, 33)) // 110
```
> Note: The type comes after the argument's name.
```go
fn full_name(first_name, last_name string) string {
return first_name + ' ' + last_name
}
println(full_name("Vitor", "Oliveira")) // Vitor Oliveira
```
## Variadic Functions
Functions can also be variadic i.e. accept an infinite number of arguments.
They are not arrays and cannot be returned.
```go
fn foo(test ...string) {
for txt in test {
println(txt)
}
}
foo("V", "is", "the", "best", "lang" , "ever")
```
Output
```console
V
is
the
best
lang
ever
```
## Multi-Return Functions
Similar to Go, functions in V can also return multiple and with a different type.
```go
fn student(name string, age int) (string, int) {
return name, age
}
name, age := student("Tom", 15)
println(name1)
println(age1)
```
Output
```console
Tom, 15
```
## High Order Functions
Functions in V can also take in another function as a parameter which is usually
needed for something like sort, map, filter, etc.
```go
fn square(num int) int {
return num * num
}
fn run(value int, op fn(int) int) int {
return op(value)
}
println(run(10, square)) // 100
```
## Naming Rules
The following are the rules which should be kept in mind while naming functions.
- Name should not contain Uppercase letters like `AlphaTest`
- Use underscores as separators like `hello_world`
- Name should not start with `_`
- Name should be descriptive as possible
- Name should not contain `__`
- Name should not contain any space
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.
### Valid Names
```go
fn i_am_valid()
fn thisworkstoo()
fn print_values_through_struct()
```
### Invalid Names
```go
fn IamNotValid()
fn _print()
fn print__logs()
fn new Make Lexer()
```
## Exercises
1. Write a V program to find the square of any number using the function.
2. Write a V program to check a given number is even or odd using the function.
3. Write a V program to convert decimal number to binary number using the function.
4. Write a V program to check whether a number is a prime number or not using the function.
5. Write a V program to get the largest element of an array using the function.
================================================
FILE: fr/section_3/methods.md
================================================
---
version: 1.0.0
example_title: Methods
---
# Methods
V does not have classes. But one can define methods for types.
A method is a function that has a special receiver argument,
only a receiver of the specified type can execute this function.
The receiver has its own argument list between `fn` and the method name.
```go
struct User {
name string
email string
mut:
age int
}
fn (u User) can_register() bool {
return u.age > 15
}
fn (u mut User) has_birthday() {
u.age += 1
}
fn main() {
mut bob := User {
name: 'Bob'
email: 'bob@bob.com'
age: 15
}
alice := User {
name: 'Alice'
email: 'alice@alice-mail.com'
age: 17
}
println(bob.can_register())
println("Bob needs to be 16 to register, but he only is ${bob.age}.")
println(alice.can_register())
bob.has_birthday()
println(bob.age)
}
```
Output
```console
false
Bob needs to be 16 to register, but he only is 15.
true
16
```
This code above realizes two methods for receivers `u` of type `User`.
Note that the method `has_birthday()` has a `mut` receiver, this is needed here since we want to change its data.
The convention of V is not to use receiver names like `self`, `this` or similar things but a short, preferably one letter long, name.
## Exercises
1. Create a method for the type `Person` that determines whether a person is underage or not.
2. Create a method that determines whether an `Animal` has fur or not.
================================================
FILE: fr/section_3/struct.md
================================================
---
version: 1.0.0
example_title: Struct
---
# Struct
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.
For people coming from [OOP](https://en.wikipedia.org/wiki/Object-oriented_programming) languages, it can be thought as `class` but with more restrictions.
```go
struct User {
name string
email string
country string
}
fn main() {
user := User {
name: "V developers"
email: "developers@vlang.io"
country: "Canada"
}
println(user.country)
}
```
> Note: Structs are allocated on the stack.
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.
```go
user := User { name: "V developers", email: "developers@vlang.io", country: "Canada" }
```
## The `&` prefix
You can also allocate a struct on the heap and get a reference to it by using the `&` prefix as follows:
```go
user := &User{"V developers", "developers@vlang.io", "Canada"}
println(user.name)
```
The type of `user` is `&User`. It's a reference to `User`.
## Access modifiers
Struct fields are `private` and `immutable` by default. Their access modifiers can be changed with `pub` and `mut`.
```go
struct User {
email string // private and immutable (default)
}
```
You can define them as `private mutable`.
```go
struct User {
email string
mut:
first_name string // private mutable
last_name string // (you can list multiple fields with the same access modifier)
}
```
You can also define them as `public immmutable` (readonly).
```go
struct User {
email string
mut:
first_name string
last_name string
pub:
sin_number int // public immutable (readonly)
}
```
or as `public`, but `mutable` only in the parent module.
```go
struct User {
email string
mut:
first_name string
last_name string
pub:
sin_number int
pub mut:
phone int // public, but mutable only in parent module
}
```
or `public` and `mutable` both inside and outside parent module.
```go
struct User {
email string
mut:
first_name string
last_name string
pub:
sin_number int
pub mut:
phone int
__global:
address_1 string // public and mutable both inside and outside parent module
address_2 string // (not recommended to use, that's why the 'global' keyword
city string // starts with __)
country string
zip string
}
```
## Naming Rules
- The name of the `struct` should always be capital.
- Use [`Snake_Case`](https://github.com/v-community/v_by_example/blob/master/en/examples/section_1/variables.md#naming-rules) for variable naming.
## Exercises
1. Create a struct that stores and displays `User` information.
2. Create a `Point` struct that holds `x` and `y` field and guard them with private and public.
================================================
FILE: fr/section_4/README.md
================================================
# Section 4
================================================
FILE: fr/section_4/array-functions.md
================================================
---
version: 1.0.0
example_title: Array Functions
---
# Array Functions
## `repeat`
Syntax
```go
array.repeat(number type)
```
Makes an array with the given element number of times.
```go
foo := [1, 2].repeat(5)
println(foo) // [1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
```
## `delete`
Syntax
```go
array.delete(ix type)
```
Deletes the element present in the array at index `ix`.
```go
mut even_numbers := [2, 4, 6, 8, 10]
even_numbers.delete(3)
println(even_numbers) // [2, 4, 6, 10]
```
## `reverse`
Syntax
```go
array.reverse()
```
Reverses the array.
```go
float_num := [1.1, 1.3, 1.25, 1.4]
float_num.reverse() // [1.4, 1.25, 1.3, 1.1]
```
## `clone`
Syntax
```go
array.clone()
```
Clones and returns a new array.
```go
foo := [1, 2, 4, 5, 4, 6]
foo1 := foo.clone()
println(foo1) // [1, 2, 4, 5, 4, 6]
```
================================================
FILE: fr/section_4/files.md
================================================
---
version: 1.0.0
example_title: Files
---
# Files
A File in V is an abstraction of any file object accessible by the program and is closely associated with `os` library.
## Reading Files
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:
```go
import os
fn main() {
mut fp := flag.new_flag_parser(os.args)
generator := fp.string('generator', '', 'generator name')
method := fp.string('method', '', 'generator method name')
path := './data/$generator/$method'
if os.file_exists(path) {
print_generator_sample(path)
} else {
println('File does not exist')
return
}
}
fn print_generator_sample(path string) {
contents := os.read_file(path.trim_space()) or {
println('Failed to open $path')
return
}
lines := contents.split_into_lines()
length := lines.len
print_random_element(lines, length)
}
fn print_random_element(lines []string, length int) {
rand.seed(time.now().uni)
println(lines[rand.next(length-1)])
}
```
## Writing files
Writing files in V is similar to read files.
```go
import os
fn main() {
path := './data/file.txt'
text := 'Full text description.'
if contents := os.write_file(path, text) or {
println('Failed while creating file')
return
}
content_lines = read_file(path)
print(content_lines)
}
fn read_file(path string) {
contents := os.read_file(path.trim_space()) or {
println('Failed to open $path')
return
}
return contents.split_into_lines()
}
```
## Exercises
1. Write a V program to create a new file with content.
2. Write a V program to read 2 different files and display their content.
3. Read how the `os` library works in V and understand how you could use it.
4. Encode a nested json string and write a new file with the result.
================================================
FILE: fr/section_4/json.md
================================================
---
version: 1.0.0
example_title: JSON
---
# JSON
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.
JSON is completely language agnostic and that's why it's the ideal interchange format.
To read more about JSON visit: [json.org](http://json.org).
## Parsing JSON
To parse a JSON string received by another application or generated within your existing application:
```go
import json
struct Customer {
first_name string
last_name string
hometown string
}
fn main() {
customers_string := '[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro" }, { "first_name": "Don", "last_name": "Nisnoni", "hometown": "Kupang" }]'
customers := json.decode([]Customer, customers_string) or {
eprintln('Failed to parse json')
return
}
// Print the list of customers
for customer in customers {
println('$customer.first_name $customer.last_name: $customer.hometown')
}
}
```
## Generating JSON
Creating a JSON string for communication or serialization is just as simple. We decode and encode in the example below:
```go
import json
struct Customer {
first_name string
last_name string
hometown string
}
fn main() {
customer_string := '[{ "first_name": "Vitor", "last_name": "Oliveira", "hometown": "Rio de Janeiro"}]'
customer := json.decode([]Customer, customer_string) or {
eprintln('Failed to parse json')
return
}
encoded_json := json.encode(customer)
println(encoded_json)
}
```
## Exercises
1. Compare how you handle JSON in your favorite language and V.
2. Build an `Address` struct that contains address information.
3. Use the `Address` struct to decode and encode a string that contains JSON format.
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.
================================================
FILE: fr/section_4/testing.md
================================================
---
version: 1.0.0
example_title: Testing
---
# Testing
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.
## Automated tests
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.
## Tests in V
In V, all test files have to be named with the following format: `*_test.v` and the functions should start with `test_*`.
```go
// sum.v in subfolder sum
module sum
pub fn sum(a, b int) int {
return a + b
}
```
```go
// sum_test.v
import sum
fn test_sum() {
assert sum.sum(2, 3) == 5
// assert sum.sum(2, 3) == 777 // => sum_test.v:6: FAILED assertion
}
```
To execute the test, you should run `v test_sum.v`.
### Examples
1. Testing JSON structures:
```go
import json
fn test_encode_customer(){
customer := Customer{ first_name: "Vitor", last_name: "Oliveira" }
expected := '{ "first_name": "Vitor", "last_name": "Oliveira" }'
encoded_json := json.encode(customer)
assert encoded_json == expected
}
```
2. Testing files:
```go
import os
fn test_file_creation() {
file_name := './new_file.txt'
content := 'text'
os.write_file(file_name, content)
assert content.len == os.file_size(file_name)
os.rm(file_name)
}
```
================================================
FILE: id/CONTRIBUTING.md
================================================
# Contributing
## General
Please ensure your pull request adheres to the following guidelines:
* New example or improvements to existing examples are welcome.
* Please check your spelling and grammar.
## Adding a New Example
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.
Thank you for your contributions!
## Getting started with the project
### 1. Fork and clone this repository
[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/).
#### 2. Make your changes and push them
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/).
## License
This code is free to use under the terms of the MIT license.
================================================
FILE: id/README.md
================================================
# V dengan Contoh
[Brazilian Portuguese](/pt-br/README.md) | [Deutsch](/de/README.md) | [English](/en/README.md) | [Bahasa Indonesia](README.md) | [Chinese](/cn/README.md)
> Belajar V dengan Contoh
V by Example adalah pengantar langsung ke V dengan menggunakan contoh program beranotasi.
* [Contoh-contoh](examples/README.md)
* [Berkontribusi](#contributing)
* [Lisensi](#license)
Discord: [https://discord.gg/d3Qk65J](https://discord.gg/d3Qk65J)
## Bagian 1
Pengenalan V dengan menghadirkan beberapa contoh dan latihan dasar.
* [Hello World](examples/section_1/hello_world.md)
* [V Keywords](examples/section_1/keywords.md)
* [Primitives](examples/section_1/primitives.md)
* [Variables](examples/section_1/variables.md)
* [Strings](examples/section_1/strings.md)
* [Comment](examples/section_1/comment.md)
## Bagian 2
Bagian ini membahas tentang operator utama dan pernyataan bersyarat dalam V.
* [Operator](examples/section_2/operator.md)
* [If-else](examples/section_2/if-else.md)
* [Match](examples/section_2/match.md)
* [Loops](examples/section_2/loops.md)
## Bagian 3
Bagian ini membahas tentang fungsi dan metode dan dalam struktur data yang paling penting dalam V: array dan struct.
* [Functions](examples/section_3/functions.md)
* [Arrays](examples/section_3/arrays.md)
* [Struct](examples/section_3/struct.md)
* [Methods](examples/section_3/methods.md)
## Bagian 4
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.
* [Array Functions](examples/section_4/array-functions.md)
* [Testing](examples/section_4/testing.md)
* [Files](examples/section_4/files.md)
* [JSON](examples/section_4/json.md)
## Tim
Daftar pengelola/penulis saat ini:
* [Don Alfons Nisnoni](https://github.com/donnisnoni95)
* [Ivo-Balbaert](https://github.com/ibalbaert)
* [Sven Patrick Meier](https://github.com/SuicideS3ason)
* [Swastik Baranwal](https://github.com/Delta456)
* [Vitor Oliveira](https://github.com/vbrazo)
## Berkontribusi
Lihat [CONTRIBUTING.md](CONTRIBUTING.md) kami dan mulai berkontribusi hari ini. Kami biasanya memilih pengelola baru berdasarkan kontribusi
## Lisensi
[MIT](/LICENSE)
================================================
FILE: id/examples/README.md
================================================
# Contoh-contoh
================================================
FILE: id/examples/section1/README.md
================================================
# Bagian 1
- [Variabel](variables.md)
================================================
FILE: id/examples/section1/variables.md
================================================
---
version: 1.0.0
example_title: Variabel
---
# Variabel
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_).
```go
umur := 23 // int
nama := 'Alice' // string
sudah_dewasa := age > 21 // bool
println(umur) // 23
println(nama) // Alice
println(sudah_dewasa) // true
```
> Catatan: Variabel hanya dapat didefinisikan di dalam suatu fungsi. Tidak ada variabel global dan tidak ada variabel global di V.
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 `=`
```go
mut umur := 20 // mendeklarasikan umur variabel yang bisa berubah dan menetapkannya ke nilai 20.
println(umur) // 20
umur = 21 // tetapkan nilai baru ke variabel umur
println(umur) // 21
```
Meninggalkan kata kunci `mut` di sini akan menghasilkan _error_ karena nilai variabel yang _immutable_ tidak dapat diubah.
```go
fn main() {
umur = 20
println(umur)
}
```
Kode di atas akan menghasilkan _error_ selama kompilasi karena variabel `umur` tidak dideklarasikan,
```go
fn main() {
mut umur := 20 // mendeklarasikan variabel yang immutable umur dan berikan nilai 20.
println(umur) // 20
umur := 21 // ERROR
}
```
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 `=`.
Seperti Go, Kamu juga dapat menggunakan `_` untuk mengabaikan nilai saat tidak diperlukan. Biasanya digunakan dalam fungsi _multi return_.
```go
_ := "Saya tidak membutuhkan nilai ini"
println(_) // ERROR: Cannot use `_` as value
```
## Aturan Penamaan
Berikut ini adalah aturan-aturan yang harus diingat saat menamai variabel.
- Nama tidak boleh mengandung huruf besar seperti `AlphaTest`
- Gunakan garis bawah sebagai pemisah seperti `hello_world`
- Nama harus sejelas mungkin
- Nama tidak boleh mengandung `__`
- Nama tidak boleh mengandung spasi apa pun
- Jika nama lebih panjang dari 11 maka harus menggunakan `_` sebagai pemisah
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.
### Nama yang Valid
```go
boby
ayah_jhon
nomor_keluargaku
```
### Nama yang tidak Valid
```go
SayaTidakValid
new Buat
```
================================================
FILE: it/CONTRIBUTING.md
================================================
# Contributing
## General
Please ensure your pull request adheres to the following guidelines:
* New example or improvements to existing examples are welcome.
* Please check your spelling and grammar.
## Adding a New Example
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.
Thank you for your contributions!
## Getting started with the project
### 1. Fork and clone this repository
[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/).
#### 2. Make your changes and push them
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/).
## License
This code is free to use under the terms of the MIT license.
================================================
FILE: it/README.md
================================================
# V per Esempi
[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)
> Impara V per Esempi
V per Esempi è un'introduzione diretta a V, utilizzando programmi di esempio con annotazioni
* [Esempi](examples/README.md)
* [Contributi](#contributing)
* [Licenze](#license)
Discord: [https://discord.gg/vlang](https://discord.gg/vlang)
## Capitolo 1
Una introduzione a V per presentare un po' esempi base ed esercizi.
* [Hello World](examples/section_1/hello_world.md)
* [V Parole riservate](examples/section_1/keywords.md)
* [Primitive](examples/section_1/primitives.md)
* [Variabili](examples/section_1/variables.md)
* [Stringhe](examples/section_1/strings.md)
* [Commento](examples/section_1/comment.md)
## Capitolo 2
Questa sezione riguarda i principali operatori e le dichiarazioni condizionali in V.
* [Operatore](examples/section_2/operator.md)
* [If-else](examples/section_2/if-else.md)
* [Match](examples/section_2/match.md)
* [Cicli](examples/section_2/loops.md)
## Capitolo 3
Uno studio sulle funzioni, metodi e sulle più importanti strutture dati in V: array e struct.
* [Funzioni](examples/section_3/functions.md)
* [Arrays](examples/section_3/arrays.md)
* [Struct](examples/section_3/struct.md)
* [Metodi](examples/section_3/methods.md)
## Capitolo 4
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.
* [Array di Funzioni](examples/section_4/array-functions.md)
* [Fare Test](examples/section_4/testing.md)
* [File](examples/section_4/files.md)
* [JSON](examples/section_4/json.md)
## Team
Lista attuale dei manutentori/autori:
* [Don Alfons Nisnoni](https://github.com/dhonx)
* [Ivo-Balbaert](https://github.com/ibalbaert)
* [Sven Patrick Meier](https://github.com/SuicideS3ason)
* [Swastik Baranwal](https://github.com/Delta456)
* [Vitor Oliveira](https://github.com/vbrazo)
## Contributi
Guarda i nostri contributi [CONTRIBUTING.md](CONTRIBUTING.md) e inizia da oggi a contribuire anche tu. Solitamente eleggiamo nuovi manutentori in base ai contributi.
## Licenza
[MIT](/LICENSE)
================================================
FILE: it/examples/README.md
================================================
# Esempi
================================================
FILE: it/examples/section_1/README.md
================================================
# Section 1
================================================
FILE: it/examples/section_1/comment.md
================================================
---
version: 1.0.0
example_title: Commenti
---
# Commenti
V supporta i commenti su una sola riga `//` e i commenti su più righe `/* */`.
Dovrebbero essere usati per documentare il codice per far capire agli altri utenti come funziona il codice.
Può anche essere utilizzato per commentare temporaneamente il codice che dovrà essere usato in seguito.
```v
// Questo è un commento su una sola riga
/* Queto è un
* commento su più righe
* /* Questo può essere a sua volta annidato*/
*/
```
================================================
FILE: it/examples/section_1/hello_world.md
================================================
---
version: 1.0.0
example_title: Stampa formattata
---
# Stampa formattata
La stampa è gestita da varie funzioni di stream I/O. Di conseguenza bisognerebbe sapere dove usarle.
- `print`: per stampare il testo nello stream di output senza un a capo.
- `println`: come `print`, ma aggiunge automaticamente un a capo.
- `eprint`: come `print`, ma l'output finisce nello stream di errore (stderr).
- `eprintln`: come `println`, ma l'output finisce nello stream di errore (stderr).
- `panic`: restituisce l'output ed esce dal programma.
```v
print('Hello World')
print('Hello V')
```
Questo stamperà `Hello WorldHello V`
Se vuoi stampare la riga successiva, scrivendo su una nuova linea, dovresti utilizzare `\n`.
```v
print('Hello World \n')
print('Hello V ')
```
Se non vuoi usare `\n` allora, al suo posto, puoi usare `println`.
## Esercizi
Prova a togliere i commenti nel file `hello.v` e vedi cosa succede.
================================================
FILE: it/examples/section_1/keywords.md
================================================
---
version: 1.0.0
example_title: Schlüsselwörter
---
# Parole riservate
V è un linguaggio piccolo, con poche parole riservate. Ci sono circa 25 parole riservate.
| Parole riservate | nel | linguaggio di | Programmazione | V |
| --------------- | ------ | ------------------ | -------------- | --------- |
| break | const | as | continue | defer |
| else | enum | fn | for | struct |
| go | goto | if | import | return |
| type | pub | mut | in | interface |
| match | module | or | none | |
Come in altri linguaggi, queste parole riservate non possono essere usate come nomi di una variabile.
================================================
FILE: it/examples/section_1/primitives.md
================================================
---
version: 1.0.0
example_title: Datentypen
---
# Dati primitivi
V ha meno tipi di dati primitivi di Go.
## Tipi base
- bool ovvero `true` oppure `false`
- striga
- tipo intero `int`
- tipo float `float`
- rune (stinga Unicode)
## Tipi composti
- vettori `[]`.
- mappe `{}`
- strutture.
## Intero
L'intero è a sua volta classificato in `signed` e `unsigned`. `signed` significa positivo o negativo e `unsigned` significa solo positivo.
### Intero con segno
| Tipo | Dimensione | Intervallo |
| ------ | :---------: | -------------------------------------: |
| int8 | 8 bits | -128 a 2<sup>7</sup> -1 |
| int16 | 16 bits | -2<sup>15</sup> a 2<sup>15</sup> - 1 |
| int | 32 bits | -2<sup>31</sup> a 2<sup>31</sup> - 1 |
| int64 | 64 bits | -2<sup>63</sup> a 2<sup>63</sup> - 1 |
| int128 | 128 bits | -2<sup>127</sup> a 2<sup>127</sup> - 1 |
### Intero senza segno
| Tipo | Dimensione | Intervallo |
| ---- | :--------: | ------------------------: |
| byte | 8 bits | 0 bis 2<sup>7</sup> -1 |
| u16 | 16 bits | 0 bis 2<sup>15</sup> - 1 |
| u32 | 32 bits | 0 bis 2<sup>31</sup> - 1 |
| u64 | 64 bits | 0 bis 2<sup>63</sup> - 1 |
| u128 | 128 bits | 0 bis 2<sup>127</sup> - 1 |
================================================
FILE: it/examples/section_1/strings.md
================================================
---
version: 1.0.0
example_title: Strings
---
# Stringhe
In V si possono definire le stringhe usando l'operatore `:=`. Le stringhe (come altre variabili) sono immutabili di default. Si è liberi di usare `""` oppure `''` per denotare una stringa. Quando si usa `vfmt` tutte le stringhe con i doppi apici saranno convertiti a singolo apice, a meno che non contengano un carattere singolo apice.
```go
name := 'Bob'
println(name) // Bob
println(name.len) // 3
```
Per ottenre la lunghezza di una stringa si usa `.len`.
## Interpolazione di una stringa
E' possibile far interpolare una stringa con `$` davanti alla variabile:
```go
name:= 'Bob'
println('Hello $name!') // Hello Bob
```
Nel caso si abbiano espressioni complesse si può usare la sintassi `${}` per l'interpolazione:
```go
struct User {
name string
age int
}
bob := User {
name: 'Bob'
age: 17
}
println('Say Hello to a new User: ${bob.name}, ${bob.age}') // Say Hello to new User: Bob, 17
println('${bob.name}s age is higher or equal to 18: ${bob.age >= 18}') // 0 <=> number representation for false
```
## Concatenazione
Le stringhe possono essere concatenate con l'operatore `+`.
```go
text := 'Hello'
concatenated_text := text + ' World!'
println(text) // Hello
println(text + ' World!') // Hello World!
println(concatenated_text) // Hello World!
```
Per appendere alla stringa con la concatenazione si può uesare anche l'operatore `+=`. Siccome le stringhe sono immutabili per default, questo è possibile solo se sono dichiarate con `mut`.
```go
mut hello := 'Hello '
hello += 'from V!' // appende 'from V!' alla stringa salvata in hello.
println(hello) // Hello from V!
```
In V, il dato stringa è codificato usando UTF-8 e la stringa stessa è un vettore read-only di byte. Questo fa si che lo slicing, il che significa che possiamo accedere al singolo carattere letterale oppura a parti di una variabile stringa.
```go
robert := 'Robert'
bert := robert[2..robert.len-1] // bert
rob := robert[0..3] // Rob
println('The persons of interest are: $robert, $bert, $rob') // The persons of interest are: Robert, bert, Rob
```
### Note
Quando usiamo la sintassi `some_string[start..end]`, la `end` **non** è inclusa.
Tutti gli operatori in V devono avere valori dello stesso tipo da entrambi i lati. Il codice seguente non compilerà perché `age` è un `int`:
```go
age := 25
println('age = ' + age)
```
Quindi noi dobbiamo convertirlo a stringa, usando `.str()` oppure usando l'interpolazione di stringhe (come preferite):
```go
age := 25
println('age = ' + age.str()) // age = 25
println('age = $age') // age = 25
```
Per definire caratteri letterali usa: ` `` `. Le stringhe grezze possono essere definite anteponendo `r`. Non considereranno i caratteri di escape.
```go
hello := 'Hello\nWorld'
println(hello) // Hello
// World
raw_hello := r'Hello\nWorld'
println(raw_hello) // Hello\nWorld
```
================================================
FILE: it/examples/section_1/variables.md
================================================
---
version: 1.0.0
example_title: Variables
---
# Variabili
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.
```go
age := 23 // int
name := 'Alice' // string
is_adult := age > 21 // bool
println(age_str) // 23
println(name) // Alice
println(is_adult) // true
```
> Nota: Le variabili possono solo essere definite in una funzione. Non ci sono variabili globali o stati globali in V.
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 `=`.
```go
mut age := 20 // dichiaro mutabile la variabile age e le assegno il valore 20.
println(age) // 20
age = 21 // assegno un nuovo valore a age
println(age) // 21
```
Senza la parola ridervata `mut` ci darà un errore perché il valore di una variabile immutabile non può essere cambiato.
```go
fn main() {
age = 20
println(age)
}
```
Il codice sopra darà un errore durante la compilazione perché la varaibile `age` non è dichiarata,
```go
fn main() {
mut age := 20 // dichiariamo mutabile la variabile age e le assegnamo il valore 20.
println(age) // 20
age := 21 // ERROR
}
```
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 `=`.
Come in Go, puoi anche usare `_` per ignorare il valori quando non sono necessari. Di solito si usa nelle funzioni che ritornano più valori.
```go
_ := "I don't need this value"
println(_) // ERROR: Cannot use `_` as value
```
## Regole per i nomi
Le seguenti solo le regole che dovrebbero essere tenute a mente quando si danno i nomi alle variabili.
- Il nome non dovrebbe contenere leettere Maiuscole come `AlphaTest`
- Usa i trattini bassi come separatore, ad esempio `hello_world`
- Il nome dovrebbe essere il più possibile descrittivo
- Il nome non dovrebbe contenere `__`
- Il nome non dovrebbe contenere spazi
- Se il nome è più lungo di 11 caratteri allora devi usare `_` come separatore
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.
### Nomi validi
```go
boby
john_dads
myfamily_number
```
### Nomi non validi
```go
IamNotValid
new Make
```
================================================
FILE: jp/CONTRIBUTING.md
================================================
# 貢献方法
## 概要
プルリクエストを送る場合、以下のガイドラインを満たしているか確認してください。
* 新しいコード例の追加や既存コード例の改善は歓迎されます。
* スペルや文法を確認してください。
## コード例のバージョンに関する注意事項
全てのコード例には、下記のようなヘッダーを含める必要があります。
```markdown
---
version: 3.5.1
example_title: JSON操作
---
```
次のルールに従い `version` 属性の変更を行います。
* メジャー :コンテンツ全体の作成(もしくは作成し直し)。新しいコンテンツには翻訳が必要です。
* マイナー:一部のコンテンツや文章などの追加、削除。
* パッチ: スペルミスやタイプミス。おそらく翻訳を必要としないもの。
[SemVer.org](https://semver.org) のパターンにしたがいます。 これは、翻訳を必要とする新しいコンテンツを決定し、翻訳者に知らせる際に使用するため重要となります。
## 新しいコード例の追加
新しいコード例を追加するには、`./examples` の適切なディレクトリの配下に、新しいフォルダとファイル、もしくはコード例に応じたファイルを作成します。どのようなコード例を作成する予定かは、`.plan` ファイルを確認してください。保留されているコード例があれば、自由に作業を行ってください。あなたが変更した箇所を読んでレビューをしたり、共にコーディングを行いマージされるのを楽しみにしています。
ご協力に感謝いたします!
## スタートガイド
### 1. リポジトリをフォークしクローンする
[このリポジトリ](https://github.com/v-community/v_by_example/fork) をフォークし、フォークからクローンを作成します。フォークが何なのか、どのように使うのか分からない方は、[こちら](https://help.github.com/articles/fork-a-repo/)がとても参考になります。
### 2.作業を行いプッシュする
作業を行う準備は整いました。作業が完了したら、変更内容を自身のフォークにプッシュし[プルリクエスト](https://help.github.com/articles/using-pull-requests/)を送りましょう。
## ライセンス
このコードは、MITライセンスの下で自由に使用できます。
================================================
FILE: jp/README.md
================================================
# コード例で学ぶV言語
[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)
> コード例で学ぶV言語
「コード例で学ぶV言語」は、各種プログラム例を用いてV言語(以下大文字のV)をストレートに紹介します。
- [コード例](#examples)
- [貢献方法](#contributing)
- [ライセンス](#license)
Discord: [https://discord.gg/d3Qk65J](https://discord.gg/d3Qk65J)
## セクション1
いくつかの基本コード例や演習をこなしながらVを紹介します。
- [Hello World](examples/section_1/hello_world.md)
- [Vのキーワード](examples/section_1/keywords.md)
- [プリミティブ型](examples/section_1/primitives.md)
- [変数](examples/section_1/variables.md)
- [文字列](examples/section_1/strings.md)
- [コメント](examples/section_1/comment.md)
## セクション2
Vにおける主要な演算子や条件文について説明します。
- [演算子](examples/section_2/operator.md)
- [If-else文](examples/section_2/if-else.md)
- [マッチ](examples/section_2/match.md)
- [ループ](examples/section_2/loops.md)
## セクション3
関数(function)やメソッド(method)、そしてVにおける最も重要なデータ構造である配列(array)や構造体(struct)について学びます。
- [関数](examples/section_3/functions.md)
- [配列](examples/section_3/arrays.md)
- [構造体](examples/section_3/struct.md)
- [メソッド](examples/section_3/methods.md)
## セクション4
このセクションでは、Arrayオブジェクトの内部機能を詳しく学びます。他にJSON、ファイル入出力、テストの書き方についても扱います。
- [配列の関数](examples/section_4/array-functions.md)
- [テストの書き方](examples/section_4/testing.md)
- [ファイル操作](examples/section_4/files.md)
- [JSON操作](examples/section_4/json.md)
## チーム
現時点のメンテナー/著者のリストは以下のとおりです。
- [Don Alfons Nisnoni](https://github.com/dhonx)
- [Ivo-Balbaert](https://github.com/ibalbaert)
- [Sven Patrick Meier](https://github.com/SuicideS3ason)
- [Swastik Baranwal](https://github.com/Delta456)
- [Vitor Oliveira](https://github.com/vbrazo)
## 貢献方法
[CONTRIBUTING.md](CONTRIBUTING.md)を読んで、早速コントリビューションを始めましょう。私たちは新しいメンテナーを主に貢献度で選んでいます。
## ライセンス
[MIT](LICENSE)
================================================
FILE: jp/code/hello_world/hello.v
================================================
// Single line comments
/* これは複数行コメントです。
* /* このようにネストもできます。 */
*
*/
print('Hello V\n')
print('Hello World')
// 以下は出力後に自動改行します。
// println('Hello V by Example')
// eprintln('Hello V by Example')
/*println('I am Bob and I am $age old') */ // これは出力されません(`$age`が未定義のため)。
/* println(foo) */ // これも動きません(カスタムの
gitextract_30_ofps6/
├── .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
Condensed preview — 159 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (267K chars).
[
{
"path": ".github/workflows/mdlint.yml",
"chars": 341,
"preview": "name: Markdown Lint\non: [push, pull_request]\njobs:\n ubuntu-latest:\n runs-on: ubuntu-latest\n steps:\n "
},
{
"path": ".gitignore",
"chars": 227,
"preview": "*.exe\r\n*.o\r\n*.obj\r\n*.vrepl_temp.v\r\n*.tmp.c\r\na.out.tmp.c\r\n*.vrepl.v\r\n*.vrepl*\r\n.vrepl_temp\r\n\r\n.DS_Store\r\ndata/.DS_Store\r\n"
},
{
"path": ".markdownlint.json",
"chars": 103,
"preview": "{\n \"MD013\": false,\n \"MD024\": false,\n \"MD033\": false,\n \"MD040\": false,\n \"MD029\": false\n}\n"
},
{
"path": ".typo-ci.yml",
"chars": 877,
"preview": "dictionaries:\r\n - de\r\n - en\r\n - en_GB\r\n - pt_BR\r\n\r\n# Files to exclude\r\nexcluded_files:\r\n - \"*.v\"\r\n\r\n# Words to excl"
},
{
"path": ".vscode/settings.json",
"chars": 0,
"preview": ""
},
{
"path": "CHANGELOG.md",
"chars": 5401,
"preview": "# Changelog\n\n## Unreleased\n\n- [PR #66](https://github.com/v-community/v_by_example/pull/66) Update .typo-ci.yml [@dhonx]"
},
{
"path": "CONTRIBUTING.md",
"chars": 1825,
"preview": "# Contributing\n\n## General\n\nPlease ensure your pull request adheres to the following guidelines:\n\n* New example or impro"
},
{
"path": "LICENSE",
"chars": 1114,
"preview": "MIT License\r\n\r\nCopyright (c) 2020 The V Programming Language Community\r\n\r\nPermission is hereby granted, free of charge, "
},
{
"path": "README.md",
"chars": 2371,
"preview": "# V by Example\n\n**NOTE: This is very outdated and it will be updated and worked upon when V 1.0 is released.**\n\n[Brazili"
},
{
"path": "SUMMARY.md",
"chars": 5695,
"preview": "# Table of contents\n\n* [V by Example](README.md)\n* [en](en/README.md)\n * [examples](en/examples/README.md)\n * [secti"
},
{
"path": "cn/CONTRIBUTING.md",
"chars": 575,
"preview": "# 贡献\n\n## 总则\n\n请确保您的请求符合以下准则:\n\n* 欢迎新示例或对现有示例的改进。\n* 请检查你的拼写和语法。\n\n## 添加新示例\n\n要添加新示例,请在`./examples`中的相应目录下创建一个新文件夹和一个文件或一个文件(取"
},
{
"path": "cn/README.md",
"chars": 1705,
"preview": "# V举例\n\n[Brazilian Portuguese](/pt-br/README.md) | [Deutsch](/de/README.md) | [English](/en/README.md) | [Bahasa Indonesi"
},
{
"path": "cn/examples/README.md",
"chars": 5,
"preview": "# 例子\n"
},
{
"path": "cn/examples/section_1/README.md",
"chars": 6,
"preview": "# 第一节\n"
},
{
"path": "cn/examples/section_1/comment.md",
"chars": 175,
"preview": "---\nversion: 1.0.0\nexample_title: 注释\n---\n\n# 注释\n\nV支持单行注释`//`和多行注释`/**/`。\n它们应该用于记录代码,以便让其他用户知道代码是如何工作的。\n它还可以用于临时注释代码,以后必须使"
},
{
"path": "cn/examples/section_1/hello_world.md",
"chars": 614,
"preview": "---\nversion: 1.0.0\nexample_title: 格式化打印\n---\n\n# 格式化打印\n\n打印由各种I/O流函数处理。人们应该要知道如何去使用它们。\n- `print`:用于将文本打印到不带换行符的输出流。\n- `prin"
},
{
"path": "cn/examples/section_1/keywords.md",
"chars": 481,
"preview": "---\nversion: 1.0.0\nexample_title: 关键字\n---\n\n# 关键字\n\nV是一种非常小巧的语言,所以它很少有关键字。大约有25个关键字。\n\n| Keywords | in | V | Programm"
},
{
"path": "cn/examples/section_1/primitives.md",
"chars": 1097,
"preview": "---\nversion: 1.0.0\nexample_title: Primitives\n---\n\n# 基本类型\n\nV的基本类型比Go少。\n\n## 基本数据类型\n\n- bool 也就是 `true` 或者 `false`\n\n- string"
},
{
"path": "cn/examples/section_1/strings.md",
"chars": 1952,
"preview": "---\nversion: 1.0.0\nexample_title: 字符串\n---\n\n# 字符串\n\n在V中,可以使用`:=`运算符定义字符串。默认情况下,字符串(与其他变量一样)是不可变的。\n一个可以使用`\"\"`或 `''`来表示字符串。使"
},
{
"path": "cn/examples/section_1/variables.md",
"chars": 1362,
"preview": "---\nversion: 1.0.0\nexample_title: 变量\n---\n\n# 变量\n\n在V语言中,变量可以用`:=`运算符声明和初始化。变量只能以这种方式在V中声明,这意味着所有变量都有一个初始值。变量的类型是从右边的值推断出来的"
},
{
"path": "cn/examples/section_2/README.md",
"chars": 6,
"preview": "# 第二节\n"
},
{
"path": "cn/examples/section_2/if-else.md",
"chars": 1813,
"preview": "---\nversion: 1.0.0\nexample_title: If语句\n---\n\n# If语句\n\n## `if` 表达式\n\n`if`语句是一个编程条件语句,如果被证明为真,则执行块中给定的代码。下面是V中if语句的一般示例:\n\n```"
},
{
"path": "cn/examples/section_2/loops.md",
"chars": 1391,
"preview": "---\nversion: 1.0.0\nexample_title: 循环结构\n---\n\n# 循环结构\n\n在V语言中只有一种类型的循环,像Go一样,它可以在很多方面使用。\n\n## `for`循环\n\n`for`循环提供了一种快速而简单的方法来重"
},
{
"path": "cn/examples/section_2/match.md",
"chars": 1868,
"preview": "---\nversion: 1.0.0\nexample_title: Match\n---\n\n# Match\n\n## match语句\n\nmatch语句是`if-else`的简写方法。\n如果输入匹配,将执行第一个匹配分支的语句块,并返回其最后一个"
},
{
"path": "cn/examples/section_2/operator.md",
"chars": 986,
"preview": "---\nversion: 1.0.0\nexample_title: 运算符\n---\n\n# 运算符\n\nV支持以下运算符:\n\n## 基本运算符\n\n- `+` (加法) 用于 int, float和string\n\n- `-` (减法) 用于 in"
},
{
"path": "cn/examples/section_3/README.md",
"chars": 5,
"preview": "# 第三节"
},
{
"path": "cn/examples/section_3/arrays.md",
"chars": 2048,
"preview": "---\r\nversion: 1.0.0\r\nexample_title: 数组\r\n---\r\n\r\n# 数组\r\n\r\n数组是存储在连续内存位置的项的集合。它是一个聚合数据结构,旨在存储一组相同类型的对象。它是存储和访问一系列对象的最有效的数据结构。"
},
{
"path": "cn/examples/section_3/functions.md",
"chars": 2137,
"preview": "---\r\nversion: 1.0.0\r\nexample_title: 函数\r\n---\r\n\r\n# Functions\r\n\r\n函数是一个有组织、可重用的代码块,用于执行单个相关操作。\r\n函数为应用程序提供了更好的模块性和高度的代码重用。\r\n理"
},
{
"path": "cn/examples/section_3/methods.md",
"chars": 1070,
"preview": "---\r\nversion: 1.0.0\r\nexample_title: Methods\r\n---\r\n\r\n# Methods\r\n\r\nV没有Class。但是可以为类型定义方法。\r\n方法是一个具有特殊接收器参数的函数,\r\n只有指定类型的接收器才能"
},
{
"path": "cn/examples/section_3/struct.md",
"chars": 2370,
"preview": "---\r\nversion: 1.0.0\r\nexample_title: Struct\r\n---\r\n\r\n# Struct\r\n\r\nstruct是一种复合数据类型(或记录)声明,它在内存块中的一个名称下定义物理分组的变量列表,允许通过单个指针或通"
},
{
"path": "cn/examples/section_4/README.md",
"chars": 5,
"preview": "# 第四节"
},
{
"path": "cn/examples/section_4/array-functions.md",
"chars": 739,
"preview": "---\r\nversion: 1.0.0\r\nexample_title: 数组函数\r\n---\r\n\r\n# 数组函数\r\n\r\n## `repeat`\r\n\r\n语法\r\n\r\n```go\r\narray.repeat(number type)\r\n```\r\n\r"
},
{
"path": "cn/examples/section_4/files.md",
"chars": 1631,
"preview": "---\r\nversion: 1.0.0\r\nexample_title: 文件操作\r\n---\r\n\r\n# 文件操作\r\n\r\nV中的文件是程序可访问的任何文件对象的抽象,与`os`库密切相关。\r\n\r\n## 读取文件\r\n\r\n读取文件是解决计算机科学中"
},
{
"path": "cn/examples/section_4/json.md",
"chars": 1693,
"preview": "# JSON\r\n\r\nJavaScript对象表示法(JSON)是一种轻量级的数据交换格式,便于人们读写。此外,机器生成和/或解析也同样简单。\r\nJSON完全不依赖于语言,因此它是理想的交换格式。\r\n\r\n要了解更多关于JSON的信息,请访问:"
},
{
"path": "cn/examples/section_4/testing.md",
"chars": 1114,
"preview": "---\r\nversion: 1.0.0\r\nexample_title: 测试\r\n---\r\n\r\n# 测试\r\n\r\n软件开发中的测试是一个过程,其目的是评估应用程序的功能,以确定代码是否满足指定的要求,并确定问题,以确保产品具有预期的质量。\r\n\r"
},
{
"path": "code/hello_world/hello.v",
"chars": 508,
"preview": "// Single line comments\r\n\r\n/* This is a multiline comment.\r\n * /* It can also be nested. */\r\n *\r\n*/\r\n\r\n print('Hello "
},
{
"path": "code/match-statement/match_examples.v",
"chars": 1477,
"preview": "fn main() {\n numbers := create_even_numbers_to_fifty()\n println('Creating an array just containing even numbers fr"
},
{
"path": "code/methods/methods.v",
"chars": 837,
"preview": "struct User {\n\tname string\n\temail string\nmut:\n\tage int\n}\n\nfn (u User) can_register() bool {\n\treturn u.age > 15\n}\n\nfn (mu"
},
{
"path": "code/variables/primitives.v",
"chars": 939,
"preview": "fn main() {\n\ta:=byte(10)\n\tb:=u16(10000)\n\tc:=u32(1000000)\n\td:=u64(10000000000)\n\t// e:=u128(10000000000000000000000) // so"
},
{
"path": "code/variables/variables.v",
"chars": 882,
"preview": "fn main() {\n age := 23\t\t\t// int\n name := 'Alice'\t\t// string\n is_male := false\t\t// bool\n is_adult := age > 21"
},
{
"path": "de/CONTRIBUTING.md",
"chars": 1243,
"preview": "# Contributing\n\n## General\n\nPlease ensure your pull request adheres to the following guidelines:\n\n* New example or impro"
},
{
"path": "de/README.md",
"chars": 2361,
"preview": "# V mit einem Beispiel\n\n[Brazilian Portuguese](/pt-br/README.md) | [Deutsch](README.md) | [English](/en/README.md) | [Ba"
},
{
"path": "de/examples/README.md",
"chars": 11,
"preview": "# Examples\n"
},
{
"path": "de/examples/section_1/README.md",
"chars": 12,
"preview": "# Section 1\n"
},
{
"path": "de/examples/section_1/comment.md",
"chars": 517,
"preview": "---\nversion: 1.0.0\nexample_title: Kommentare\n---\n\n# Kommentare\n\nV bietet die Möglichkeit Zeilenkommentare mit `//` und m"
},
{
"path": "de/examples/section_1/hello_world.md",
"chars": 1086,
"preview": "---\nversion: 1.0.0\nexample_title: Formatted Print\n---\n\n# Formatted Print\n\nKonsolenausgaben werden durch verschiedene I/O"
},
{
"path": "de/examples/section_1/keywords.md",
"chars": 777,
"preview": "---\nversion: 1.0.0\nexample_title: Schlüsselwörter\n---\n\n# Schlüsselwörter\n\nV ist eine kleine Programmiersprache mit wenig"
},
{
"path": "de/examples/section_1/primitives.md",
"chars": 1792,
"preview": "---\nversion: 1.0.0\nexample_title: Datentypen\n---\n\n# Primitive Datentypen\n\nV hat weniger primitive Datentypen als Go.\n\n##"
},
{
"path": "de/examples/section_1/strings.md",
"chars": 3677,
"preview": "---\nversion: 1.0.0\nexample_title: Strings\n---\n\n# Strings\n\nIn V können Strings mit dem Deklarationsoperator (`:=`) deklar"
},
{
"path": "de/examples/section_1/variables.md",
"chars": 1889,
"preview": "---\nversion: 1.0.0\nexample_title: Variables\n---\n\n# Variables\n\nVariablen können in V mit dem `:=` Operator deklariert und"
},
{
"path": "de/examples/section_2/README.md",
"chars": 12,
"preview": "# Section 2\n"
},
{
"path": "de/examples/section_2/if-else.md",
"chars": 2785,
"preview": "---\nversion: 1.0.0\nexample_title: If statement\n---\n\n# If statement\n\n## The `if` statement\n\nAn `if` statement is a progra"
},
{
"path": "de/examples/section_2/loops.md",
"chars": 2405,
"preview": "---\nversion: 1.0.0\nexample_title: Looping Constructs\n---\n\n# Looping Constructs\n\nThere's only one type of loop in V langu"
},
{
"path": "de/examples/section_2/match.md",
"chars": 2355,
"preview": "---\nversion: 1.0.0\nexample_title: Match\n---\n\n# Match\n\n## The `match` statement\n\nA match statement is a short-hand way fo"
},
{
"path": "de/examples/section_2/operator.md",
"chars": 1823,
"preview": "---\nversion: 1.0.0\nexample_title: Operators\n---\n\n# Operators\n\nV bietet die folgenden Operatoren:\n\n## Grundlegende Operat"
},
{
"path": "de/examples/section_3/README.md",
"chars": 12,
"preview": "# Section 3\n"
},
{
"path": "de/examples/section_3/arrays.md",
"chars": 2941,
"preview": "---\nversion: 1.0.0\nexample_title: Arrays\n---\n\n# Arrays\n\nAn array is a collection of items stored in contiguous memory lo"
},
{
"path": "de/examples/section_3/functions.md",
"chars": 2239,
"preview": "---\nversion: 1.0.0\nexample_title: Functions\n---\n\n# Functions\n\nA function is a block of organized, reusable code that is "
},
{
"path": "de/examples/section_3/methods.md",
"chars": 1621,
"preview": "---\nversion: 1.0.0\nexample_title: Methods\n---\n\n# Methods\n\nV does not have classes. But one can define methods for types."
},
{
"path": "de/examples/section_3/struct.md",
"chars": 2474,
"preview": "---\nversion: 1.0.0\nexample_title: Struct\n---\n\n# Struct\n\nA struct is a composite data type (or record) declaration that d"
},
{
"path": "de/examples/section_4/README.md",
"chars": 12,
"preview": "# Section 4\n"
},
{
"path": "de/examples/section_4/array-functions.md",
"chars": 876,
"preview": "---\nversion: 1.0.0\nexample_title: Array Functions\n---\n\n# Array Functions\n\n## `repeat`\n\nSyntax\n\n```go\narray.repeat(number"
},
{
"path": "de/examples/section_4/files.md",
"chars": 1980,
"preview": "---\nversion: 1.0.0\nexample_title: Files\n---\n\n# Files\n\nA File in V is an abstraction of any file object accessible by the"
},
{
"path": "de/examples/section_4/json.md",
"chars": 2232,
"preview": "---\nversion: 1.0.0\nexample_title: JSON\n---\n\n# JSON\n\nJavaScript Object Notation (JSON) is a lightweight data-interchange "
},
{
"path": "de/examples/section_4/testing.md",
"chars": 1570,
"preview": "---\nversion: 1.0.0\nexample_title: Testing\n---\n\n# Testing\n\nTesting in software development is a process that aims to eval"
},
{
"path": "docs_style_guide.md",
"chars": 1030,
"preview": "# Documentation Style Guide\n\nThese are the guidelines for writing documentation.\n\n## Titles\n\n- Each page must have a s"
},
{
"path": "en/examples/section_1/README.md",
"chars": 12,
"preview": "# Section 1\n"
},
{
"path": "en/examples/section_1/comment.md",
"chars": 452,
"preview": "---\r\nversion: 1.0.0\r\nexample_title: Comments\r\n---\r\n\r\n# Comments\r\n\r\nV supports single line comments `//` and multi-line c"
},
{
"path": "en/examples/section_1/hello_world.md",
"chars": 1310,
"preview": "---\r\nversion: 1.0.0\r\nexample_title: Hello World\r\n---\r\n\r\n# Formatted Print\r\n\r\nPrinting is handled by various I/O stream f"
},
{
"path": "en/examples/section_1/keywords.md",
"chars": 596,
"preview": "---\r\nversion: 1.0.0\r\nexample_title: Keywords\r\n---\r\n\r\n# Keywords\r\n\r\nV is a very small language so it has few keywords. Th"
},
{
"path": "en/examples/section_1/primitives.md",
"chars": 1298,
"preview": "---\r\nversion: 1.0.0\r\nexample_title: Primitives\r\n---\r\n\r\n# Primitives\r\n\r\nV has less primitive types than Go.\r\n\r\n## Basic T"
},
{
"path": "en/examples/section_1/strings.md",
"chars": 2909,
"preview": "---\nversion: 1.0.0\nexample_title: Strings\n---\n\n# Strings\n\nIn V one can define strings using the `:=` operator. Strings ("
},
{
"path": "en/examples/section_1/variables.md",
"chars": 2568,
"preview": "---\nversion: 1.0.0\nexample_title: Variables\n---\n\n# Variables\n\nIn V variables can be declared and initialized with the `:"
},
{
"path": "en/examples/section_2/README.md",
"chars": 12,
"preview": "# Section 2\n"
},
{
"path": "en/examples/section_2/if-else.md",
"chars": 2806,
"preview": "---\nversion: 1.0.0\nexample_title: If statement\n---\n\n# If statement\n\n## The `if` statement\n\nAn `if` statement is a progra"
},
{
"path": "en/examples/section_2/loops.md",
"chars": 2520,
"preview": "---\r\nversion: 1.0.0\r\nexample_title: Loops\r\n---\r\n\r\n# Looping Constructs\r\n\r\nThere's only one type of loop in V language, l"
},
{
"path": "en/examples/section_2/match.md",
"chars": 2355,
"preview": "---\nversion: 1.0.0\nexample_title: Match\n---\n\n# Match\n\n## The `match` statement\n\nA match statement is a short-hand way fo"
},
{
"path": "en/examples/section_2/operator.md",
"chars": 1435,
"preview": "---\nversion: 1.0.0\nexample_title: Operators\n---\n\n# Operators\n\nV supports the following operators:\n\n## Basic Operators\n\n-"
},
{
"path": "en/examples/section_3/README.md",
"chars": 12,
"preview": "# Section 3\n"
},
{
"path": "en/examples/section_3/arrays.md",
"chars": 2948,
"preview": "---\nversion: 1.0.0\nexample_title: Arrays\n---\n\n# Arrays\n\nAn array is a collection of items stored in contiguous memory lo"
},
{
"path": "en/examples/section_3/functions.md",
"chars": 2974,
"preview": "---\nversion: 1.0.0\nexample_title: Functions\n---\n\n# Functions\n\nA function is a block of organized, reusable code that is "
},
{
"path": "en/examples/section_3/methods.md",
"chars": 1490,
"preview": "---\nversion: 1.0.0\nexample_title: Methods\n---\n\n# Methods\n\nV does not have classes. But one can define methods for types."
},
{
"path": "en/examples/section_3/struct.md",
"chars": 3053,
"preview": "---\nversion: 1.0.0\nexample_title: Struct\n---\n\n# Struct\n\nA struct is a composite data type (or record) declaration that d"
},
{
"path": "en/examples/section_4/README.md",
"chars": 12,
"preview": "# Section 4\n"
},
{
"path": "en/examples/section_4/array-functions.md",
"chars": 822,
"preview": "---\nversion: 1.0.0\nexample_title: Array Functions\n---\n\n# Array Functions\n\n## `repeat`\n\nSyntax\n\n```go\narray.repeat(number"
},
{
"path": "en/examples/section_4/files.md",
"chars": 1980,
"preview": "---\nversion: 1.0.0\nexample_title: Files\n---\n\n# Files\n\nA File in V is an abstraction of any file object accessible by the"
},
{
"path": "en/examples/section_4/json.md",
"chars": 2232,
"preview": "---\nversion: 1.0.0\nexample_title: JSON\n---\n\n# JSON\n\nJavaScript Object Notation (JSON) is a lightweight data-interchange "
},
{
"path": "en/examples/section_4/testing.md",
"chars": 1570,
"preview": "---\nversion: 1.0.0\nexample_title: Testing\n---\n\n# Testing\n\nTesting in software development is a process that aims to eval"
},
{
"path": "fr/section_1/Beinvenue_monde.md",
"chars": 1558,
"preview": "---\r\nversion: 1.0.0\r\ntitre de l'example: Hello World\r\n---\r\n\r\n# imprimé formaté\r\n\r\nL'impression est assurée par diverses "
},
{
"path": "fr/section_1/README.md",
"chars": 12,
"preview": "# Section 1\n"
},
{
"path": "fr/section_1/les_chaînes de caractères.md",
"chars": 2909,
"preview": "---\nversion: 1.0.0\nexample_title: Strings\n---\n\n# Strings\n\nIn V one can define strings using the `:=` operator. Strings ("
},
{
"path": "fr/section_1/les_commentaires.md",
"chars": 452,
"preview": "---\r\nversion: 1.0.0\r\nexample_title: Comments\r\n---\r\n\r\n# Comments\r\n\r\nV supports single line comments `//` and multi-line c"
},
{
"path": "fr/section_1/les_mots_clés.md",
"chars": 596,
"preview": "---\r\nversion: 1.0.0\r\nexample_title: Keywords\r\n---\r\n\r\n# Keywords\r\n\r\nV is a very small language so it has few keywords. Th"
},
{
"path": "fr/section_1/les_primitives.md",
"chars": 1298,
"preview": "---\r\nversion: 1.0.0\r\nexample_title: Primitives\r\n---\r\n\r\n# Primitives\r\n\r\nV has less primitive types than Go.\r\n\r\n## Basic T"
},
{
"path": "fr/section_1/les_variables.md",
"chars": 2568,
"preview": "---\nversion: 1.0.0\nexample_title: Variables\n---\n\n# Variables\n\nIn V variables can be declared and initialized with the `:"
},
{
"path": "fr/section_2/README.md",
"chars": 12,
"preview": "# Section 2\n"
},
{
"path": "fr/section_2/if-else.md",
"chars": 2806,
"preview": "---\nversion: 1.0.0\nexample_title: If statement\n---\n\n# If statement\n\n## The `if` statement\n\nAn `if` statement is a progra"
},
{
"path": "fr/section_2/loops.md",
"chars": 2520,
"preview": "---\r\nversion: 1.0.0\r\nexample_title: Loops\r\n---\r\n\r\n# Looping Constructs\r\n\r\nThere's only one type of loop in V language, l"
},
{
"path": "fr/section_2/match.md",
"chars": 2355,
"preview": "---\nversion: 1.0.0\nexample_title: Match\n---\n\n# Match\n\n## The `match` statement\n\nA match statement is a short-hand way fo"
},
{
"path": "fr/section_2/operator.md",
"chars": 1435,
"preview": "---\nversion: 1.0.0\nexample_title: Operators\n---\n\n# Operators\n\nV supports the following operators:\n\n## Basic Operators\n\n-"
},
{
"path": "fr/section_3/README.md",
"chars": 12,
"preview": "# Section 3\n"
},
{
"path": "fr/section_3/arrays.md",
"chars": 2948,
"preview": "---\nversion: 1.0.0\nexample_title: Arrays\n---\n\n# Arrays\n\nAn array is a collection of items stored in contiguous memory lo"
},
{
"path": "fr/section_3/functions.md",
"chars": 2974,
"preview": "---\nversion: 1.0.0\nexample_title: Functions\n---\n\n# Functions\n\nA function is a block of organized, reusable code that is "
},
{
"path": "fr/section_3/methods.md",
"chars": 1490,
"preview": "---\nversion: 1.0.0\nexample_title: Methods\n---\n\n# Methods\n\nV does not have classes. But one can define methods for types."
},
{
"path": "fr/section_3/struct.md",
"chars": 3053,
"preview": "---\nversion: 1.0.0\nexample_title: Struct\n---\n\n# Struct\n\nA struct is a composite data type (or record) declaration that d"
},
{
"path": "fr/section_4/README.md",
"chars": 12,
"preview": "# Section 4\n"
},
{
"path": "fr/section_4/array-functions.md",
"chars": 822,
"preview": "---\nversion: 1.0.0\nexample_title: Array Functions\n---\n\n# Array Functions\n\n## `repeat`\n\nSyntax\n\n```go\narray.repeat(number"
},
{
"path": "fr/section_4/files.md",
"chars": 1980,
"preview": "---\nversion: 1.0.0\nexample_title: Files\n---\n\n# Files\n\nA File in V is an abstraction of any file object accessible by the"
},
{
"path": "fr/section_4/json.md",
"chars": 2232,
"preview": "---\nversion: 1.0.0\nexample_title: JSON\n---\n\n# JSON\n\nJavaScript Object Notation (JSON) is a lightweight data-interchange "
},
{
"path": "fr/section_4/testing.md",
"chars": 1570,
"preview": "---\nversion: 1.0.0\nexample_title: Testing\n---\n\n# Testing\n\nTesting in software development is a process that aims to eval"
},
{
"path": "id/CONTRIBUTING.md",
"chars": 1243,
"preview": "# Contributing\n\n## General\n\nPlease ensure your pull request adheres to the following guidelines:\n\n* New example or impro"
},
{
"path": "id/README.md",
"chars": 2242,
"preview": "# V dengan Contoh\n\n[Brazilian Portuguese](/pt-br/README.md) | [Deutsch](/de/README.md) | [English](/en/README.md) | [Bah"
},
{
"path": "id/examples/README.md",
"chars": 16,
"preview": "# Contoh-contoh\n"
},
{
"path": "id/examples/section1/README.md",
"chars": 39,
"preview": "# Bagian 1\n\n- [Variabel](variables.md)\n"
},
{
"path": "id/examples/section1/variables.md",
"chars": 2793,
"preview": "---\nversion: 1.0.0\nexample_title: Variabel\n---\n\n# Variabel\n\nVariabel pada V dapat dinyatakan dan diinisialisasi dengan `"
},
{
"path": "it/CONTRIBUTING.md",
"chars": 1243,
"preview": "# Contributing\n\n## General\n\nPlease ensure your pull request adheres to the following guidelines:\n\n* New example or impro"
},
{
"path": "it/README.md",
"chars": 2295,
"preview": "# V per Esempi\n\n[Brasiliano Portughese](/pt-br/README.md) | [Tedesco](/de/README.md) | [Inglese](/en/README.md) | [Bahas"
},
{
"path": "it/examples/README.md",
"chars": 9,
"preview": "# Esempi\n"
},
{
"path": "it/examples/section_1/README.md",
"chars": 12,
"preview": "# Section 1\n"
},
{
"path": "it/examples/section_1/comment.md",
"chars": 491,
"preview": "---\nversion: 1.0.0\nexample_title: Commenti\n---\n\n# Commenti\n\nV supporta i commenti su una sola riga `//` e i commenti su "
},
{
"path": "it/examples/section_1/hello_world.md",
"chars": 922,
"preview": "---\nversion: 1.0.0\nexample_title: Stampa formattata\n---\n\n# Stampa formattata\n\nLa stampa è gestita da varie funzioni di s"
},
{
"path": "it/examples/section_1/keywords.md",
"chars": 829,
"preview": "---\nversion: 1.0.0\nexample_title: Schlüsselwörter\n---\n\n# Parole riservate\n\nV è un linguaggio piccolo, con poche parole r"
},
{
"path": "it/examples/section_1/primitives.md",
"chars": 1311,
"preview": "---\nversion: 1.0.0\nexample_title: Datentypen\n---\n\n# Dati primitivi\n\nV ha meno tipi di dati primitivi di Go.\n\n## Tipi bas"
},
{
"path": "it/examples/section_1/strings.md",
"chars": 3118,
"preview": "---\nversion: 1.0.0\nexample_title: Strings\n---\n\n# Stringhe\n\nIn V si possono definire le stringhe usando l'operatore `:=`."
},
{
"path": "it/examples/section_1/variables.md",
"chars": 2804,
"preview": "---\nversion: 1.0.0\nexample_title: Variables\n---\n\n# Variabili\n\nIn V le variabili possono essere dichiarate e inizializzat"
},
{
"path": "jp/CONTRIBUTING.md",
"chars": 1092,
"preview": "# 貢献方法\n\n## 概要\n\nプルリクエストを送る場合、以下のガイドラインを満たしているか確認してください。\n\n* 新しいコード例の追加や既存コード例の改善は歓迎されます。\n* スペルや文法を確認してください。\n\n## コード例のバージョン"
},
{
"path": "jp/README.md",
"chars": 1799,
"preview": "# コード例で学ぶV言語\n\n[Brazilian Portuguese](pt-br/README.md) | [Deutsch](de/README.md) | [English](en/README.md) | [Bahasa Indo"
},
{
"path": "jp/code/hello_world/hello.v",
"chars": 412,
"preview": "// Single line comments\r\n\r\n/* これは複数行コメントです。\r\n * /* このようにネストもできます。 */\r\n *\r\n*/\r\n\r\n print('Hello V\\n')\r\n print('Hello"
},
{
"path": "jp/examples/section_1/README.md",
"chars": 187,
"preview": "# セクション1\n\nいくつかの基本コード例や演習をこなしながらVを紹介します。\n\n- [Hello World](hello_world.md)\n- [Vのキーワード](keywords.md)\n- [プリミティブ型](primitives"
},
{
"path": "jp/examples/section_1/comment.md",
"chars": 242,
"preview": "---\nversion: 1.0.0\nexample_title: コメント\n---\n\n# コメント\n\nVでは単一行コメント`//`と複数行コメント`/* */`をサポートしています。\nこれらのコメントは、コードのしくみを他のユーザーに理解"
},
{
"path": "jp/examples/section_1/hello_world.md",
"chars": 871,
"preview": "---\nversion: 1.0.0\nexample_title: hello world\n---\n\n# 書式付き出力(formatted print)\n\nprintによる出力は、さまざまなI/Oストリーム関数で用いられます。以下の違いにつ"
},
{
"path": "jp/examples/section_1/keywords.md",
"chars": 498,
"preview": "---\nversion: 1.0.0\nexample_title: キーワード\n---\n\n# キーワード\n\nVはきわめて小規模な言語なのでキーワードもごくわずか(25個程度)しかありません。\n\n| V | 言語 | に "
},
{
"path": "jp/examples/section_1/primitives.md",
"chars": 1165,
"preview": "---\nversion: 1.0.0\nexample_title: プリミティブ型\n---\n\n# プリミティブ型\n\nVのプリミティブ型は、Go言語よりも少なくなっています。\n\n## 基本型\n\n- bool型(`true`または`false`"
},
{
"path": "jp/examples/section_1/strings.md",
"chars": 2284,
"preview": "---\nversion: 1.0.0\nexample_title: 文字列\n---\n\n# 文字列\n\nVでは文字列の定義も`:=`演算子で行えます。他の変数と同様、文字列もデフォルトでイミュータブルです。文字列を(リテラルとして)表現するとき"
},
{
"path": "jp/examples/section_1/variables.md",
"chars": 1671,
"preview": "---\nversion: 1.0.0\nexample_title: 変数\n---\n\n# 変数\n\nVの変数は`:=`演算子で宣言および初期化できます。Vの変数はこれ以外の方法では宣言できません。つまり、いかなる変数にも初期値が存在するというこ"
},
{
"path": "jp/examples/section_2/README.md",
"chars": 119,
"preview": "# セクション2\n\nVにおける主要な演算子や条件文について説明します。\n\n- [演算子](operator.md)\n- [If-else文](if-else.md)\n- [マッチ](match.md)\n- [ループ](loops.md)\n"
},
{
"path": "jp/examples/section_2/if-else.md",
"chars": 1996,
"preview": "---\nversion: 1.0.0\nexample_title: if文\n---\n\n# if文\n\n## `if`文\n\n`if`文は、プログラミングにおける条件を記述する文であり、trueの場合は指定のブロック内のコードを実行します。以下は"
},
{
"path": "jp/examples/section_2/loops.md",
"chars": 1611,
"preview": "---\nversion: 1.0.0\nexample_title: ループを書く\n---\n\n# ループを書く\n\nV言語のループ構文は1種類しかありません。Goでもこのループ構文は広く使われています。\n\n## `for`ループ\n\n`for`ル"
},
{
"path": "jp/examples/section_2/match.md",
"chars": 2055,
"preview": "---\nversion: 1.0.0\nexample_title: マッチ\n---\n\n# マッチ\n\n## `match`文\n\n`match`文は`if - else`文のショートハンドです。\n入力がマッチすると、選択肢の中で最初にマッチした"
},
{
"path": "jp/examples/section_2/operator.md",
"chars": 1117,
"preview": "---\nversion: 1.0.0\nexample_title: 演算子\n---\n\n# 演算子\n\nVでサポートされる演算子は以下のとおりです。\n\n## 基本演算子\n\n- `+`(加算)int、float、stringが対象\n\n- `-`("
},
{
"path": "jp/examples/section_3/README.md",
"chars": 168,
"preview": "# セクション3\n\n関数(function)やメソッド(method)、そしてVにおける最も重要なデータ構造である配列(array)や構造体(struct)について学びます。\n\n- [関数](functions.md)\n- [配列](arr"
},
{
"path": "jp/examples/section_3/arrays.md",
"chars": 2222,
"preview": "---\nversion: 1.0.0\nexample_title: 配列\n---\n\n# 配列\n\n配列(array)は、メモリ上の連続した位置に保存された項目のコレクションです。配列は、型が同じであるオブジェクトのグループを保存するよう設計さ"
},
{
"path": "jp/examples/section_3/functions.md",
"chars": 2045,
"preview": "---\nversion: 1.0.0\nexample_title: 関数\n---\n\n# 関数\n\n関数とは、再利用可能な形に整えられたコードのブロックであり、単一の作業を実行します。\n関数はアプリケーションのモジュラリティを高め、コードをより"
},
{
"path": "jp/examples/section_3/methods.md",
"chars": 1143,
"preview": "---\nversion: 1.0.0\nexample_title: メソッド\n---\n\n# メソッド\n\nVにはクラスというものはありません。しかし型に対してメソッドを定義できます。\n\nメソッド(method)とは、1個のレシーバーを特殊な引"
},
{
"path": "jp/examples/section_3/struct.md",
"chars": 2564,
"preview": "---\nversion: 1.0.0\nexample_title: 構造体\n---\n\n# 構造体\n\n構造体(struct)は、さまざまなデータ型(レコード)を組み合わせて宣言します。構造体は、さまざまな変数のリストをメモリの1つのブロックの"
},
{
"path": "jp/examples/section_4/README.md",
"chars": 174,
"preview": "# セクション4\n\nこのセクションでは、Arrayオブジェクトの内部機能を詳しく学びます。他にJSON、ファイル入出力、テストの書き方についても扱います。\n\n- [配列の関数](array-functions.md)\n- [テストの書き方]"
},
{
"path": "jp/examples/section_4/array-functions.md",
"chars": 762,
"preview": "---\nversion: 1.0.0\nexample_title: 配列の関数\n---\n\n# 配列の関数\n\n## `repeat`\n\n構文\n\n```go\narray.repeat(number type)\n```\n\n配列の要素を指定の回数だ"
},
{
"path": "jp/examples/section_4/files.md",
"chars": 1673,
"preview": "---\nversion: 1.0.0\nexample_title: ファイル操作\n---\n\n# ファイル操作\n\nVでは、ファイルを「プログラムからアクセス可能な任意のファイルオブジェクトの抽象化」としており、`os`ライブラリと深く関連して"
},
{
"path": "jp/examples/section_4/json.md",
"chars": 1825,
"preview": "---\nversion: 1.0.0\nexample_title: JSON操作\n---\n\n# JSON操作\n\nJSON(JavaScript Object Notation)は、人間にとって読み書きしやすい軽量なデータ交換フォーマットです"
},
{
"path": "jp/examples/section_4/testing.md",
"chars": 1168,
"preview": "---\nversion: 1.0.0\nexample_title: テストの書き方\n---\n\n# テストの書き方\n\nソフトウェア開発におけるテストは、コードが特定の要求を満たしていることを確認してアプリケーションが意図したとおりに動作するか"
},
{
"path": "pt-br/CONTRIBUTING.md",
"chars": 1331,
"preview": "# Contribuindo\n\n## Geral\n\nVerifique se sua solicitação de alteração segue as seguintes regras:\n\n* Novos exemplos ou melh"
},
{
"path": "pt-br/README.md",
"chars": 1285,
"preview": "# V por exemplos\n\n[Brazilian Portuguese](README.md) | [Deutsch](/de/README.md) | [English](/en/README.md) | [Bahasa Indo"
},
{
"path": "pt-br/examples/README.md",
"chars": 11,
"preview": "# Exemplos\n"
},
{
"path": "pt-br/examples/section_1/README.md",
"chars": 12,
"preview": "# Section 1\n"
},
{
"path": "pt-br/examples/section_1/comment.md",
"chars": 521,
"preview": "---\nversion: 1.0.0\nexample_title: Comentários\n---\n\n# Comentários\n\nV suporta comentários de linha única `//` e comentário"
},
{
"path": "pt-br/examples/section_1/keywords.md",
"chars": 642,
"preview": "---\nversion: 1.0.0\nexample_title: Palavras-chave\n---\n\n# Palavras-chave\n\nV é uma linguagem muito pequena, por isso possui"
},
{
"path": "pt-br/examples/section_1/primitives.md",
"chars": 1272,
"preview": "---\nversion: 1.0.0\nexample_title: Primitivos\n---\n\n# Primitivos\n\nV tem menos tipos primitivos que Go.\n\n## Tipos básicos\n\n"
},
{
"path": "pt-br/examples/section_2/README.md",
"chars": 12,
"preview": "# Section 2\n"
},
{
"path": "pt-br/examples/section_2/operators.md",
"chars": 1459,
"preview": "---\nversion: 1.0.0\nexample_title: Operadores\n---\n\n# Operadores\n\nV suporta os seguintes operadores:\n\n## Operadores básico"
}
]
About this extraction
This page contains the full source code of the v-community/v_by_example GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 159 files (211.8 KB), approximately 72.3k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.