search
HomeWeb Front-endHTML TutorialThe keyword of Go element is located--chan channel

HTML validate refers to HTML validation. It is a process of analyzing HTML documents and marking errors and non-standard code by comparing them with standard HTML rules. Web pages are rendered using HTML, and HTML itself adopts HTML specifications as its rules and standards. Validate HTML code across multiple browser standards!

chan

chan is also called a channel, which is similar in form to a pipe. The content is sent in from one end and read out from the other end. The following describes how to define a channel:

var 变量名 chan dataType

When defining a channel, you need to specify the data type, which means that only variables of the specified data type are allowed to pass through the channel.

Initialize channel

In golang, when initializing channel type variables, the channel can be divided into two situations, one is a buffered channel, and the other is Unbuffered channel.
Let’s introduce the initialization methods in the following two situations:

// 初始化不带缓冲的通道,通道中数据类型是intvar ch1 = make(chan int)// 初始化带10个缓冲的通道,通道中数据类型是stringvar ch2 = make(chan string,10)

Another way to write it is to define and initialize the channel,

// 定义通道,并给通道初始化8个缓冲ch3 := make(chan int ,8)// 定义通道,并初始化为不带缓冲通道ch4 := make(chan string)

Channel assignment

Both reading and writing to the channel may enter a blocking state.

  1. Unbuffered channels will block when writing. The blocking will not end until the information in the channel is read.

  2. For a buffered channel, each time information is written to the channel, the channel length will be increased by 1. Each time information is successfully read from the channel, the channel length will be decreased by 1. If the channel length is equal to the channel buffer length, continuing to write information to the channel will cause the program to block; if the channel length is less than the channel buffer length, writing information to the channel will not cause blocking. If the channel length is 5, then writing information to the channel for the sixth time will cause the program to block when the channel has not been read.

The syntax format for channel writing is:

var ch = make(chan string,10)// 将字符串”hello"写入到通道中,通道长度加1ch <- "hello"

Read channel

The channel is empty
1. If the channel is not closed, the program will enter the blocking state and wait until the channel has information written
2. The channel has been closed and will not be blocked. The initial value of the data type in the channel (dirty data) is returned. For example, when the channel is chan int, the return value is 0. When the channel is chan string, the return value is empty.
The channel is not empty
1. The channel is not closed. Read the information from the channel once. After the reading is completed, continue execution
2. The channel has been closed. Read the information from the channel once. After the reading is completed, proceed to the

read channel operation:

val,ok := <-ch

Use assertion to read the channel The value in , checks whether the channel still has content, and determines whether the channel has been closed. When there is no information in the channel and the channel has been closed, the ok value is false. When the channel is not closed, but there is no information in the channel, the program will block. , if there is content in the channel, the ok value is true.

Another way to read a channel without using assertions

val := <-ch

Writing and reading channels

Reading an unbuffered channel example Method:

package mainimport (    "fmt")func main() {    // 定义一个不带缓冲的通道,通道中数据类型是int
    var c = make(chan int)    // 开启一个携程,读取通道中的内容
    go func() {
        fmt.Println("写入信息是:", <-c)
    }()    // 向通道中写入数据
    c <- 1}

Output result:

写入信息是: 1

When reading and writing a buffered channel, as long as the data length in the channel is not greater than the buffer length, there will be no blocking, but when reading the buffered channel, there will be no blocking. For buffered channels, when there is no content in the channel, the program will still enter the blocking state. Therefore, buffered channels only affect writes. Here is an example:

package mainimport (    "fmt")func main() {    var c = make(chan int, 3)
    c <- 1
    c <- 2
    c <- 3
    //c <- 4
    fmt.Println("end")
}

The output information is:

end

When writing content to a channel with 3 buffers, since it is only written 3 times, the length of the channel is exactly equal to The length of the buffer means that the program is not blocked. When the comment in front of c

Coroutine communication

The channel type variable is essentially an address, as shown in the following example code:

package mainimport (    "fmt")func main() {    var c = make(chan int, 3)
    fmt.Println(c)
}

Output result:

0xc042072080

So, when the channel type variable is passed into the function as a parameter, the value in the channel can be directly modified in the function. Although the chan type variable is an address, golang does not allow the use of the value operator (*) to operate the chan type variable. But if you first use the address operator (&) on the chan type variable, and then use the value operator (*), this operation method can still run normally, but it does not mean much unless your purpose is In the function call, redefine a chan type variable to replace the original variable.

These features of chan can effectively realize the synchronization function between coroutines. The unbuffered channel is a zero-tolerance waiting, which can achieve forced synchronization; the buffered channel is a certain amount of tolerance waiting, and can achieve synchronization that allows a certain time difference.

Simple example of inter-coroutine communication:

package mainimport (    "fmt"
    "time")func main() {    var c = make(chan int)    go func() {
        fmt.Println("待命模式:")        // 读取通道时产生阻塞,等待其他协程向通道写入信息
        fmt.Println("命令代码是:", <-c)
    }()    go func() {        // 延时3秒,向通道中写入信息
        time.Sleep(time.Second * 3)
        fmt.Println("发送命令:")
        c <- 8
        close(c)
    }()
    time.Sleep(time.Second * 5)
    fmt.Println("执行完成")
}

The output information is:

待命模式:
发送命令:
命令代码是: 8
执行完成

Related recommendations:

HTML validate HTML validation_HTML /Xhtml_Web page production

HTML skills compilation_CSS/HTML

The above is the detailed content of The keyword of Go element is located--chan channel. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
HTML as a Markup Language: Its Function and PurposeHTML as a Markup Language: Its Function and PurposeApr 22, 2025 am 12:02 AM

The function of HTML is to define the structure and content of a web page, and its purpose is to provide a standardized way to display information. 1) HTML organizes various parts of the web page through tags and attributes, such as titles and paragraphs. 2) It supports the separation of content and performance and improves maintenance efficiency. 3) HTML is extensible, allowing custom tags to enhance SEO.

The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.