1660807638
In this tutorial, we'll learn about Flyte, Kubernetes-native workflow automation platform for complex, mission-critical data and ML processes at scale. It has been battle-tested at Lyft, Spotify, Freenome, and others and is truly open-source.
💻 🛳 🚀
Code. Ship. Scale.
Flyte is a workflow automation platform for complex, mission-critical data, and ML processes at scale
Flyte is a structured programming and distributed processing platform that enables highly concurrent, scalable, and maintainable workflows for Machine Learning
and Data Processing
. It is a fabric that connects disparate computation backends using a type-safe data dependency graph. It records all changes to a pipeline, making it possible to rewind time. It also stores a history of all executions and provides an intuitive UI, CLI, and REST/gRPC API to interact with the computation.
Flyte is more than a workflow engine -- it uses workflow
as a core concept, and task
(a single unit of execution) as a top-level concept. Multiple tasks arranged in a data producer-consumer order creates a workflow.
Workflows
and Tasks
can be written in any language, with out-of-the-box support for Python, Java and Scala. Flyte was designed to manage the complexity that arises in Data and ML teams and ensure they keep up their high velocity of delivering business impacting features. One way it achieves this is by separating the control-plane from the user-plane. Thus, every organization can offer Flyte as a service to their end-users where the service is managed by folks who are more infrastructure-focused, while the users use the intuitive interface of Flytekit.
![]() |
---|
✨ Flyte UI ✨ |
Repo | Language | Purpose | Status |
---|---|---|---|
flyte | Kustomize,RST | deployment, documentation, issues | Production-grade |
flyteidl | Protobuf | gRPC/REST API, Workflow language spec | Production-grade |
flytepropeller | Go | execution engine | Production-grade |
flyteadmin | Go | control plane | Production-grade |
flytekit | Python | python SDK and tools | Production-grade |
flyteconsole | Typescript | Flyte UI | Production-grade |
datacatalog | Go | manage input & output artifacts | Production-grade |
flyteplugins | Go | Flyte Backend plugins | Production-grade |
flytecopilot | Go | Sidecar to manage input/output for sdk-less | Production-grade |
flytestdlib | Go | standard library | Production-grade |
flytesnacks | Python | examples, tips, and tricks | Maintained |
flytekit-java | Java/Scala | Java & scala SDK for authoring Flyte workflows | Incubating |
flytectl | Go | A standalone Flyte CLI | Production-grade |
homebrew-tap | Ruby | Tap for downloadable flyte tools (cli etc) | Production-grade |
bazel-rules | skylark/py | Use Bazel to build Flyte workflows and tasks | Incubating |
We run a suite of tests to ensure that basic functionality and a subset of the integrations work across a variety of release versions. Those tests are run in a cluster where specific versions of the Flyte components (such as flyteconsole, flyteadmin, datacatalog, and flytepropeller) are installed, including the released versions and also the latest versions in the case of the nighly runs.
The table below has different release versions as the columns and the result of each test suite as rows:
workflow group | nightly | v1.0.1 | v1.0.0 | v0.19.4 |
---|---|---|---|---|
core | ||||
integrations-hive | ||||
integrations-k8s-spark | ||||
integrations-kfpytorch | ||||
integrations-pod | ||||
integrations-pandera_examples | ||||
integrations-papermilltasks | ||||
integrations-greatexpectations | ||||
integrations-sagemaker-pytorch | ||||
integrations-sagemaker-training |
Flyte is a community-driven and community-owned software. It is managed using a steering committee and encourages collaboration. The community has a long roadmap for Flyte, but there might be interesting ideas, extensions, or additions that you may want to propose. This is usually done by starting with:
RFCs are encouraged for larger changes. You are welcome to hop into our Slack and talk to the community if you want to test the waters before proposing.
Download Details:
Author: flyteorg
Source Code: https://github.com/flyteorg/flyte
License: Apache-2.0
#python #kubernetes #golang #datascience #machine #flyte
1660678440
Static Site Generator with Go backend and Svelte frontend
You must have NodeJS version 13 or newer As of v0.2.0
you no longer need NodeJS, Go, or any dependency other than Plenti itself.
Homebrew:
brew tap plentico/homebrew-plenti
brew install plenti
Snap:
snap install plenti
Scoop (Windows is not supported yet, see details):
scoop bucket add plenti https://github.com/plentico/scoop-plenti
scoop install plenti
Manual:
PATH
(most likely /usr/local/bin
)plenti new site my-new-site
cd my-new-site
plenti serve
Plenti is brand new and needs to be test driven a bit to work out the kinks. If you find bugs or have any questions, please open a new issue to let us know! Thank you for being patient while Plenti grows :seedling:
Author: plentico
Source code: https://github.com/plentico/plenti
License: Apache-2.0 license
#svetle #javascript #go #golang
1660631520
Gór: Go in Rust
A very incomplete implementation of Go written as an interpreter in Rust.
This package contains a high-level library interface and the command-line executable.
$ cat hello.go
package main
import "fmt"
func main() {
fmt.Println("hello world")
}
$ cargo build
Finished dev [unoptimized + debuginfo] target(s) in 0.08s
$ target/debug/gor hello.go
Error: Runtime Error
Caused by:
Can't static eval "Can't actually evaluate functions yet"
If valid Go code fails to parse, that's a bug. Or possibly a missing feature, depending on how far I've got so far -- examples of all parseable control structures should be found in tests/compile
.
Our currently-incomplete module loader should be able to load modules from anywhere the Go compiler can find them.
Not all invalid Go programs will be rejected by gor
. If an invalid Go program is accepted, the (minor) bug is that we accepted the code, rather than any run-time failures that might ensue.
Missing "standard" modules are missing features rather than bugs.
If all required modules and syntax are available, running a Go program in gor
should provide the same side-effects as compiling it with go
and running the resulting binary. If it does not then that's a bug.
The CLI currently evaluates expressions. It should match Go's precedence rules.
We currently only really support i64 and bool types.
We have no support for any control structures.
Go modules dropped into tests/compile
will be parsed as part of cargo test
. We use build.rs
to generate Rust test cases.
Eventually™ we'll have compile-failure, compile-only, and executable tests.
Not a priority
According to Wikipedia, Gór was the brother of Nór, who founded Norway. This project is called Gór, in his honour and because his name contains both "go" and "r". Crates can only contain ASCII, and as a result use the name gor
. The default executable takes the name of the crate and is therefore also gor
. To avoid confusion, please try to avoid capitalising the executable name or missing off the accent in the project name.
The "ó" is short, the "r" should be rolled if you're able.
To generate the ó, on Linux type <Compose>
-'
-a
. The compose key is usually <Shift>
-<Alt-Gr>
, although I recommend configuring your environment to use a plain <Alt-Gr>
. On a Mac, type <Option>
-e
then o
.
If this all feels a bit too awkward for me to be serious about it, I recommend reading Patrick McKenzie's falsehoods programmers believe about names and then considering how easy you have it if your name is trivially representable in all the systems you use on a regular basis.
Author: andrewaylett
Source code: https://github.com/andrewaylett/gor
#rust #rustlang #go #golang
1660417080
To check if the string is a substring of another string in Go, use the contains() method.
Golang String Contains() is a built-in function that checks whether substr is within the string. The Contains() function accepts two arguments and returns the boolean value, either true or false.
To use Contains() function in Go, import the strings package and then call the contains() method and pass the two parameters in which one is a source string and the second is the substring, which we need to check against the main string
See more at: https://appdividend.com/2022/06/07/golang-string-contains/
#golang #go
1660406220
Чтобы проверить, является ли строка подстрокой другой строки в Go, используйте метод contains().
Golang String Contains() — это встроенная функция, которая проверяет, находится ли substr в строке. Функция Contains() принимает два аргумента и возвращает логическое значение, либо true , либо false .
Чтобы использовать функцию Contains() в Go , импортируйте пакет strings , затем вызовите метод contains() и передайте два параметра, один из которых является исходной строкой, а второй — подстрокой, которую нам нужно сравнить с основной строкой.
func Contains(s, substr string) bool
Первый параметр — это исходная строка, а второй параметр — это подстрока, которую мы должны сравнить с основной строкой, чтобы увидеть, содержит ли она ее.
Метод strings.Contains() возвращает логическое значение true или false.
См. следующий код.
// hello.go
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Contains("MichaelJackson", "Michael"))
fmt.Println(strings.Contains("MillieBobbyBrown", "Bobby"))
fmt.Println(strings.Contains("AudreyGraham", "Drake"))
fmt.Println(strings.Contains("Jennifer Lopez", "JLo"))
}
go run hello.go
true
true
false
false
С «Содержит» мы ищем в одной строке указанную подстроку. Затем мы видим, найдена ли строка.
В приведенном выше примере подстрока появляется в основной строке в первых двух тестовых случаях. Вот почему он возвращает true.
Исходная строка не содержит подстроки в последних двух тестовых примерах. Вот почему он возвращает false.
Мы ищем символы с помощью других строковых функций , таких как функция ContainsAny() . Если в строке найден какой-либо набор символов, ContainsAny вернет значение true.
См. следующий код.
// hello.go
package main
import (
"fmt"
"strings"
)
func main() {
dataA := "Javascript"
dataB := "Golang"
source := "this is a Golang"
if strings.Contains(source, dataA) {
fmt.Println("JavaScript")
}
if strings.Contains(source, dataB) {
fmt.Println("Golang")
}
}
go run hello.go
Golang
У нас есть строка, содержащая «Этот язык — Голанг». Однако слово «Javascript» в строке не найдено. Итак, мы получаем false для первого теста.
Когда мы вызываем Contains и ищем String Golang, он возвращает true, потому что строка содержит подстроку Golang. Поэтому он возвращает true и печатает строку.
strings.Contains () более точен, чем Index(), когда нам нужно проверить существование. Мы можем проверить истинность и ложность, а не волшебное значение -1, которое Index() возвращает, чтобы означать «не найдено».
Ссылка: https://appdividend.com/2022/06/07/golang-string-contains/
#go #golang
1660405680
EVM-compatible chain secured by the Lachesis consensus algorithm.
Building opera
requires both a Go (version 1.14 or later) and a C compiler. You can install them using your favourite package manager. Once the dependencies are installed, run
make opera
The build output is build/opera
executable.
opera
Going through all the possible command line flags is out of scope here, but we've enumerated a few common parameter combos to get you up to speed quickly on how you can run your own opera
instance.
You will need a genesis file to join a network, which may be found in https://github.com/Fantom-foundation/lachesis_launch
Launching opera
readonly (non-validator) node for network specified by the genesis file:
$ opera --genesis file.g
As an alternative to passing the numerous flags to the opera
binary, you can also pass a configuration file via:
$ opera --config /path/to/your_config.toml
To get an idea how the file should look like you can use the dumpconfig
subcommand to export your existing configuration:
$ opera --your-favourite-flags dumpconfig
New validator private key may be created with opera validator new
command.
To launch a validator, you have to use --validator.id
and --validator.pubkey
flags to enable events emitter.
$ opera --nousb --validator.id YOUR_ID --validator.pubkey 0xYOUR_PUBKEY
opera
will prompt you for a password to decrypt your validator private key. Optionally, you can specify password with a file using --validator.password
flag.
Optionally you can specify your public IP to straighten connectivity of the network. Ensure your TCP/UDP p2p port (5050 by default) isn't blocked by your firewall.
$ opera --nat extip:1.2.3.4
The network is specified only by its genesis file, so running a testnet node is equivalent to using a testnet genesis file instead of a mainnet genesis file:
$ opera --genesis /path/to/testnet.g # launch node
It may be convenient to use a separate datadir for your testnet node to avoid collisions with other networks:
$ opera --genesis /path/to/testnet.g --datadir /path/to/datadir # launch node
$ opera --datadir /path/to/datadir account new # create new account
$ opera --datadir /path/to/datadir attach # attach to IPC
Lachesis has extensive unit-testing. Use the Go tool to run tests:
go test ./...
If everything goes well, it should output something along these lines:
ok github.com/Fantom-foundation/go-opera/app 0.033s
? github.com/Fantom-foundation/go-opera/cmd/cmdtest [no test files]
ok github.com/Fantom-foundation/go-opera/cmd/opera 13.890s
? github.com/Fantom-foundation/go-opera/cmd/opera/metrics [no test files]
? github.com/Fantom-foundation/go-opera/cmd/opera/tracing [no test files]
? github.com/Fantom-foundation/go-opera/crypto [no test files]
? github.com/Fantom-foundation/go-opera/debug [no test files]
? github.com/Fantom-foundation/go-opera/ethapi [no test files]
? github.com/Fantom-foundation/go-opera/eventcheck [no test files]
? github.com/Fantom-foundation/go-opera/eventcheck/basiccheck [no test files]
? github.com/Fantom-foundation/go-opera/eventcheck/gaspowercheck [no test files]
? github.com/Fantom-foundation/go-opera/eventcheck/heavycheck [no test files]
? github.com/Fantom-foundation/go-opera/eventcheck/parentscheck [no test files]
ok github.com/Fantom-foundation/go-opera/evmcore 6.322s
? github.com/Fantom-foundation/go-opera/gossip [no test files]
? github.com/Fantom-foundation/go-opera/gossip/emitter [no test files]
ok github.com/Fantom-foundation/go-opera/gossip/filters 1.250s
? github.com/Fantom-foundation/go-opera/gossip/gasprice [no test files]
? github.com/Fantom-foundation/go-opera/gossip/occuredtxs [no test files]
? github.com/Fantom-foundation/go-opera/gossip/piecefunc [no test files]
ok github.com/Fantom-foundation/go-opera/integration 21.640s
Also it is tested with fuzzing.
Fakenet is a private network optimized for your private testing. It'll generate a genesis containing N validators with equal stakes. To launch a validator in this network, all you need to do is specify a validator ID you're willing to launch.
Pay attention that validator's private keys are deterministically generated in this network, so you must use it only for private testing.
Maintaining your own private network is more involved as a lot of configurations taken for granted in the official networks need to be manually set up.
To run the fakenet with just one validator (which will work practically as a PoA blockchain), use:
$ opera --fakenet 1/1
To run the fakenet with 5 validators, run the command for each validator:
$ opera --fakenet 1/5 # first node, use 2/5 for second node
If you have to launch a non-validator node in fakenet, use 0 as ID:
$ opera --fakenet 0/5
After that, you have to connect your nodes. Either connect them statically or specify a bootnode:
$ opera --fakenet 1/5 --bootnodes "enode://verylonghex@1.2.3.4:5050"
For the testing purposes, the full demo may be launched using:
cd demo/
./start.sh # start the Opera processes
./stop.sh # stop the demo
./clean.sh # erase the chain data
Check README.md in the demo directory for more information.
Author: Fantom-foundation
Source code: https://github.com/Fantom-foundation/go-opera
License: MIT license
#fantom #blockchain #go #golang
1660395360
要檢查字符串是否是 Go 中另一個字符串的子字符串,請使用 contains() 方法。
Golang String Contains()是一個內置函數,用於檢查 substr 是否在字符串中。Contains() 函數接受兩個參數並返回布爾值true或false。
要在Go中使用Contains()函數,請導入strings包,然後調用 contains() 方法並傳遞兩個參數,其中一個是源字符串,第二個是子字符串,我們需要對照主字符串檢查。
func Contains(s, substr string) bool
第一個參數是源字符串,第二個參數是子字符串,我們必須對照主字符串檢查它是否包含。
strings.Contains() 方法返回布爾值true 或 false。
請參閱以下代碼。
// hello.go
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Contains("MichaelJackson", "Michael"))
fmt.Println(strings.Contains("MillieBobbyBrown", "Bobby"))
fmt.Println(strings.Contains("AudreyGraham", "Drake"))
fmt.Println(strings.Contains("Jennifer Lopez", "JLo"))
}
go run hello.go
true
true
false
false
使用包含,我們在一個字符串中搜索指定的子字符串。然後,我們看看是否找到了字符串。
在上面的示例中,子字符串出現在前兩個測試用例的主字符串中。這就是它返回true 的原因。
源字符串不包含最後兩個測試用例中的子字符串。這就是它返回false 的原因。
我們使用其他字符串函數(如 ContainsAny()函數)搜索字符。如果在字符串中找到任何字符集, ContainsAny 將返回 true。
請參閱以下代碼。
// hello.go
package main
import (
"fmt"
"strings"
)
func main() {
dataA := "Javascript"
dataB := "Golang"
source := "this is a Golang"
if strings.Contains(source, dataA) {
fmt.Println("JavaScript")
}
if strings.Contains(source, dataB) {
fmt.Println("Golang")
}
}
go run hello.go
Golang
我們有一個包含“This language is Golang”的字符串。但是,在字符串中沒有找到“Javascript”這個詞。因此,我們收到第一個測試用例的錯誤。
當我們調用 Contains 並蒐索 String Golang 時,它會返回 true,因為該字符串包含 Golang 子字符串。所以它返回 true 並打印該行。
當我們需要測試存在性時, strings.Contains()比 Index() 更精確。我們可以檢查真假,而不是 Index() 返回表示“未找到”的神奇值 -1。
鏈接:https ://appdividend.com/2022/06/07/golang-string-contains/
#go #golang
1660384500
Để kiểm tra xem chuỗi có phải là chuỗi con của một chuỗi khác trong Go hay không, hãy sử dụng phương thức chứa ().
Golang String Contains () là một hàm tích hợp để kiểm tra xem substr có nằm trong chuỗi hay không. Hàm Contains () chấp nhận hai đối số và trả về giá trị boolean, true hoặc false .
Để sử dụng hàm Contains () trong Go , hãy nhập gói chuỗi và sau đó gọi phương thức chứa () và chuyển hai tham số, trong đó một tham số là chuỗi nguồn và tham số thứ hai là chuỗi con, mà chúng ta cần kiểm tra với chuỗi chính.
func Contains(s, substr string) bool
Tham số đầu tiên là một chuỗi nguồn và tham số thứ hai là chuỗi con, mà chúng ta phải kiểm tra chuỗi chính để xem nó có chứa hay không.
Phương thức string.Contains () trả về giá trị boolean true hoặc false.
Xem đoạn mã sau.
// hello.go
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Contains("MichaelJackson", "Michael"))
fmt.Println(strings.Contains("MillieBobbyBrown", "Bobby"))
fmt.Println(strings.Contains("AudreyGraham", "Drake"))
fmt.Println(strings.Contains("Jennifer Lopez", "JLo"))
}
go run hello.go
true
true
false
false
Với Chứa, chúng tôi tìm kiếm một chuỗi cho một chuỗi con được chỉ định. Sau đó, chúng tôi xem nếu chuỗi được tìm thấy.
Trong ví dụ trên, chuỗi con xuất hiện trong chuỗi chính trong hai trường hợp thử nghiệm đầu tiên. Đó là lý do tại sao nó trả về true.
Chuỗi nguồn không chứa chuỗi con trong hai trường hợp thử nghiệm cuối cùng. Đó là lý do tại sao nó trả về false.
Chúng tôi tìm kiếm các ký tự có các hàm chuỗi khác như hàm ContainsAny () . Nếu tìm thấy bất kỳ bộ ký tự nào trong chuỗi, ContainsAny sẽ trả về true.
Xem đoạn mã sau.
// hello.go
package main
import (
"fmt"
"strings"
)
func main() {
dataA := "Javascript"
dataB := "Golang"
source := "this is a Golang"
if strings.Contains(source, dataA) {
fmt.Println("JavaScript")
}
if strings.Contains(source, dataB) {
fmt.Println("Golang")
}
}
go run hello.go
Golang
Chúng tôi có một chuỗi Chứa "Ngôn ngữ này là Golang." Tuy nhiên, từ “Javascript” không được tìm thấy trong chuỗi. Vì vậy, chúng tôi nhận được sai cho trường hợp thử nghiệm đầu tiên.
Khi chúng ta gọi Contains và tìm kiếm Chuỗi Golang, nó trả về true vì chuỗi chứa chuỗi con Golang. Vì vậy, nó trả về true và in dòng.
Các string.Contains () chính xác hơn Index () khi chúng ta cần kiểm tra sự tồn tại. Chúng ta có thể kiểm tra true và false, không phải giá trị ma thuật -1 mà Index () trả về có nghĩa là “không tìm thấy”.
Liên kết: https://appdividend.com/2022/06/07/golang-string-contains/
#go #golang
1660383480
GraphQL API server for Fantom Artion v2 - backend for Artion-Client-V2.
Build using make:
make
Create JSON config file by doc/config.example.json
example.
Requirements for run:
node.url
in config file.db
section of config file.shared_db
section.ipfs.url
ipfs.gateway
ipfs.gateway_bearer
(even when local IPFS node is used otherwise!)notification.sendgrid
section.Before first start you need to initialize the MongoDB database. If you want to use other than the official contracts on mainnet, you will need to update observed.json
appropriately first.
mongoimport --db=artion --collection=observed --file=doc/db/observed.json
mongoimport --db=artion --collection=status --file=doc/db/status.json
For the shared MongoDB database:
mongoimport --db=artionshared --collection=colcats --file=doc/db/colcats.json
mongoimport --db=artionshared --collection=collections --file=doc/db/collections.json
When configured, run the Artion api server:
build/artionapi -cfg my-config-file.json
For production deployment check systemd example in doc/systemd
to install the api server as systemd service.
As soon as the api server is started, you can access GraphiQL testing interface at http://localhost:7373/graphi.
To connect Artion-Client-V2 update the providers list in app.config.js
to use http://localhost:7373/graphql
.
Author: Fantom-foundation
Source code: https://github.com/Fantom-foundation/Artion-API-GraphQL
License: GPL-3.0 license
#fantom #blockchain #api #graphql #go #golang
1660373475
Pour vérifier si la chaîne est une sous-chaîne d'une autre chaîne dans Go, utilisez la méthode contains().
Golang String Contient() est une fonction intégrée qui vérifie si substr se trouve dans la chaîne. La fonction Contient() accepte deux arguments et renvoie la valeur booléenne, true ou false .
Pour utiliser la fonction Contient() dans Go , importez le package de chaînes , puis appelez la méthode contains() et transmettez les deux paramètres dans lesquels l'un est une chaîne source et le second est la sous-chaîne, que nous devons vérifier par rapport à la chaîne principale.
func Contains(s, substr string) bool
Le premier paramètre est une chaîne source et le deuxième paramètre est la sous-chaîne, que nous devons vérifier par rapport à la chaîne principale pour voir si elle contient.
La méthode strings.Contains() renvoie la valeur booléenne true ou false.
Voir le code suivant.
// hello.go
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Contains("MichaelJackson", "Michael"))
fmt.Println(strings.Contains("MillieBobbyBrown", "Bobby"))
fmt.Println(strings.Contains("AudreyGraham", "Drake"))
fmt.Println(strings.Contains("Jennifer Lopez", "JLo"))
}
go run hello.go
true
true
false
false
Avec Contient, nous recherchons une chaîne pour une sous-chaîne spécifiée. Ensuite, nous voyons si la chaîne est trouvée.
Dans l'exemple ci-dessus, la sous-chaîne apparaît dans la chaîne principale dans les deux premiers cas de test. C'est pourquoi il renvoie vrai.
La chaîne source ne contient pas la sous-chaîne dans les deux derniers cas de test. C'est pourquoi il renvoie faux.
Nous recherchons des caractères avec d'autres fonctions de chaîne comme la fonction ContientAny() . Si un ensemble de caractères est trouvé dans la chaîne, containsAny renverra true.
Voir le code suivant.
// hello.go
package main
import (
"fmt"
"strings"
)
func main() {
dataA := "Javascript"
dataB := "Golang"
source := "this is a Golang"
if strings.Contains(source, dataA) {
fmt.Println("JavaScript")
}
if strings.Contains(source, dataB) {
fmt.Println("Golang")
}
}
go run hello.go
Golang
Nous avons une chaîne qui contient "Cette langue est Golang." Cependant, le mot "Javascript" n'a pas été trouvé dans la chaîne. Ainsi, nous recevons un faux pour le premier cas de test.
Lorsque nous appelons Contient et recherchons la chaîne Golang, elle renvoie true car la chaîne contient la sous-chaîne Golang. Il renvoie donc true et imprime la ligne.
Le strings.Contains () est plus précis que Index () lorsque nous devons tester l'existence. Nous pouvons vérifier par vrai et faux, pas la valeur magique -1 que Index() renvoie pour signifier « introuvable ».
Lien : https://appdividend.com/2022/06/07/golang-string-contains/
#go #golang
1660355226
I created this Golang tutorial to be the definitive course. I provide in this full course more information than you can get in any book. The table of contents follows below. Both the core language and numerous projects are provided to help you master Go.
Go is one of the fastest growing languages and for good reason. Go makes it very easy to write fast code without having to tweak with the code. The code is understandable, efficient, excels at concurrency, provides great backend support for web apps, handles errors much like Rust and manages memory efficiently.
TABLE OF CONTENTS
00:00 Intro
01:44 Package
02:15 Import
02:42 Alias
03:19 Comments
03:40 Main
04:27 User Input
06:00 Error Handling
06:35 Blank Identifier
07:33 Variables
10:19 Data Types
12:12 Casting
12:30 Casting Strings
17:33 If Conditional
20:56 Strings
29:19 Runes
31:15 Printf
33:15 Time
34:39 Math
44:35 For Loop
46:25 While Loop
53:16 Range
54:23 Arrays
1:01:18 Slices
1:08:29 Functions
1:10:20 Return Multiple
1:11:05 Function Errors
1:13:11 Varadic Functions
1:14:35 Passing Arrays
1:17:50 Pointers
1:21:35 Pass Array Pointers
1:26:09 File IO
1:37:11 Command Line
1:43:03 Packages / Modules
1:52:40 Maps
1:59:27 Generics
2:00:38 Constraints
2:04:24 Structs
2:12:04 Composition
2:16:05 Defined types
2:21:54 Associate Methods
2:24:50 Protecting Data
2:25:12 Getter / Setter
2:31:00 Encapsulation
2:33:42 Interfaces
2:38:39 Concurrency / GoRoutines
2:40:49 Sleep
2:42:10 Channels
2:45:16 Mutex / Lock
2:51:13 Closures
2:53:13 Passing Functions
2:55:50 Recursion
2:58:59 Regular Expressions
3:07:00 Automated Testing
3:16:42 Web app
3:38:44 Templates / HTML
3:45:16 Installation
Get the Code : https://github.com/derekbanas/Go-Tutorial
#go #golang
1660332960
A function is a mapping of zero or more input parameters to zero or more output parameters. Go functions are first-class citizens. Functions can be assigned to variables, passed as arguments to functions or returned from functions.
Functions in Go are created with the func keyword. We use the return keyword to return values from functions. The body of the function consists of statements that are executed when the function is called. The body is delimited with a pair of curly brackets {}. To call a function, we specify its name followed by round bracktets (). A function may or may not take parameters.
package main
import "fmt"
func main() {
x := 4
y := 5
z := add(x, y)
fmt.Printf("Output: %d\n", z)
}
func add(a int, b int) int {
return a + b
}
In the code example, we define a function which adds two values.
z := add(x, y)
We call the add
function; it takes two parameters. The computed value is passed to the z
variable.
func add(a int, b int) int {
return a + b
}
We define the add
function. The parameters of the function are separated with comma; each parameter name is followed with its data type. After the parameters, we specify the return value type. The statements that are executed when the function is called are placed between curly brackets. The result of the addition operation is returned to the caller with the return
keyword.
$ go run simple_fun.go
Output: 9
1660329240
Command-line arguments are options and data that are passed to programs. We usually pass arguments to console programs, but sometimes we pass arguments to GUI programs as well.
The os.Args
holds the command-line arguments. The first value in this slice is the name of the program, while the os.Args[1:]
holds the arguments to the program. The individual arguments are accessed with indexing operation.
package main
import (
"fmt"
"os"
"reflect"
)
func main() {
prg_name := os.Args[0]
fmt.Printf("The program name is %s\n", prg_name)
names := os.Args[1:]
fmt.Println(reflect.TypeOf(names))
for _, name := range names {
fmt.Printf("Hello, %s!\n", name)
}
}
The example receives command-line arguments.
prg_name := os.Args[0]
fmt.Printf("The program name is %s\n", prg_name)
We get and print the first argument, which is the program name.
names := os.Args[1:]
We get all the received arguments.
fmt.Println(reflect.TypeOf(names))
We print the type which holds the arguments (slice).
for _, name := range names {
fmt.Printf("Hello, %s!\n", name)
}
We go through the arguments and build a message from each of them.
$ go build read_args.go
$ ./read_args Jan Peter Lucia
The program name is ./read_args
[]string
Hello, Jan!
Hello, Peter!
Hello, Lucia!
We build the program and run it. We pass the program three names on the command line.
1660321860
Go switch statement provides a multi-way execution. An expression or type specifier is compared to the cases inside the switch to determine which branch to execute. Unlike in other languages such as C, Java, or PHP, each case is terminated by an implicit break; therefore, we do not have to write it explicitly.
The default statement can be used for a branch that is executed, when no other cases fit. The default statement is optional.
package main
import (
"fmt"
"runtime"
)
func main() {
os := runtime.GOOS
switch os {
case "windows":
fmt.Println("Windows")
case "darwin":
fmt.Println("MAC operating system")
case "linux":
fmt.Println("Linux")
default:
fmt.Printf("%s.\n", os)
}
}
The GOOS
environment variable is the running program's operating system target: one of darwin, freebsd, linux, and so on. Based on the value of the variable, we print the OS version.
$ go run get_os.go
Linux
1660318140
The for statement specifies repeated execution of a block.
package main
import "fmt"
func main() {
sum := 0
for i := 0; i < 10; i++ {
sum += i
}
fmt.Println(sum)
}
This is the classic C-style for statement. The program calculates the sum of values 1..9.
for i := 0; i < 10; i++ {
sum += i
}
The for statement consists of three parts: the initialization, the condition, and the increment. The initialization part is executed only once. The body of the for statement is executed when the condition is true. If the condition returns false, the for loop is terminated. After the statements in the block are executed, the for loop switches to the third part, where the counter is incremented. The cycle continues until the condition is not true anymore. Note that is it possible to create endless loops.
$ go run for_loop.go
45
The sum of values 1..9 is 45.
The following example uses the for
loop with the range
keyword.
package main
import "fmt"
func main() {
nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
sum := 0
for _, num := range nums {
sum += num
}
fmt.Println(sum)
}
This example calculates the sum of array values.
nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
We define an array of values.
for _, num := range nums {
sum += num
}
We iterate over the array with the range
clause. The range
returns the index and the value in each iteration. Since we do not use the index, we specify the discard _
operator. (The Golang documentation calls it the blank identifier.)