Home Backend Development Python Tutorial Go language comparison C++ reference parameter passing

Go language comparison C++ reference parameter passing

Sep 02, 2017 am 11:16 AM
Compared Quote language

This article mainly introduces whether Go has parameter passing by reference (compared to C++). Friends who need it can refer to

Three parameter passing methods in C++

Value passing:

The most common method of passing parameters. The formal parameters of the function are copies of the actual parameters. Changing the formal parameters in the function will not affect to formal parameters outside the function. Generally, value passing is used when modifying parameters within a function without affecting the caller.

Pointer passing

The formal parameter is a pointer pointing to the address of the actual parameter. As the name suggests, when the content pointed to by the formal parameter is manipulated in the function, the actual parameter itself will be modified. .

Passing by reference

In C++, a reference is an alias for a variable. It is actually the same thing and has the same address in memory. In other words, wherever a reference is manipulated, the referenced variable is quite directly manipulated.

Look at the demo below:


#include <iostream>
//值传递
void func1(int a) {
  std::cout << "值传递,变量地址:" << &a << ", 变量值:" << a << std::endl;
  a ++ ;
}
//指针传递
void func2 (int* a) {
  std::cout << "指针传递,变量地址:" << a << ", 变量值:" << *a << std::endl;
  *a = *a + 1;
}
//引用传递
void func3 (int& a) {
  std::cout << "指针传递,变量地址:" << &a << ", 变量值:" << a << std::endl;
  a ++;
}
int main() {
  int a = 5;
  std::cout << "变量实际地址:" << &a << ", 变量值:" << a << std::endl;
  func1(a);
  std::cout << "值传递操作后,变量值:" << a << std::endl;
  std::cout << "变量实际地址:" << &a << ", 变量值:" << a << std::endl;
  func2(&a);
  std::cout << "指针传递操作后,变量值:" << a << std::endl;
  std::cout << "变量实际地址:" << &a << ", 变量值:" << a << std::endl;
  func3(a);
  std::cout << "引用传递操作后,变量值:" << a << std::endl;
  return 0;
}
Copy after login

The output results are as follows:

Actual address of variable: 0x28feac, variable value: 5
value Transfer, variable address: 0x28fe90, variable value: 5
After the value transfer operation, variable value: 5
Actual variable address: 0x28feac, variable value: 5
Pointer transfer, variable address: 0x28feac, variable value: 5
After the pointer transfer operation, the variable value: 6
The actual address of the variable: 0x28feac, the variable value: 6
The pointer transfer operation, the variable address: 0x28feac, the variable value: 6
After the reference transfer operation, the variable Value: 7

Parameter passing in Go

The above introduces the three parameter passing methods of C++, value passing and pointer Passing is easy to understand, so does Go also have these parameter passing methods? This has caused controversy, but compared to the concept of reference passing in C++, we can say that Go has no reference passing method. Why do I say this, because Go does not have the concept of variable references. But Go has reference types, which will be explained later.

Let’s first look at an example of passing value and pointer in Go:


package main
import (
  "fmt"
)
func main() {
  a := 1
  fmt.Println( "变量实际地址:", &a, "变量值:", a)
  func1 (a)
  fmt.Println( "值传递操作后,变量值:", a)
  fmt.Println( "变量实际地址:", &a, "变量值:", a)
  func2(&a)
  fmt.Println( "指针传递操作后,变量值:", a)
}
//值传递
func func1 (a int) {
  a++
  fmt.Println( "值传递,变量地址:", &a, "变量值:", a)
}
//指针传递
func func2 (a *int) {
  *a = *a + 1
  fmt.Println( "指针传递,变量地址:", a, "变量值:", *a)
}
Copy after login

The output result is as follows:

The actual address of the variable: 0xc04203c1d0 variable Value: 1
Value transfer, variable address: 0xc04203c210 Variable value: 2
After value transfer operation, variable value: 1
Actual variable address: 0xc04203c1d0 Variable value: 1
Pointer transfer, variable address: 0xc04203c1d0 Variable value: 2
After the pointer transfer operation, variable value: 2
It can be seen that the value transfer and pointer transfer of Go's basic types are no different from C++, but it does not have the concept of variable reference. So how do you understand Go's reference types?

Go’s reference types

In Go, reference types include slices, dictionaries, channels, etc. Take slicing as an example. Is passing a slice a reference?

For example:


package main
import (
  "fmt"
)
func main() {
  m1 := make([]string, 1)
  m1[0] = "test"
  fmt.Println("调用 func1 前 m1 值:", m1)
  func1(m1)
  fmt.Println("调用 func1 后 m1 值:", m1)
}
func func1 (a []string) {
  a[0] = "val1"
  fmt.Println("func1中:", a)
}
Copy after login

The output result is as follows:

The value of m1 before calling func1: [test]

## In #func1: [val1]

The value of m1 after calling func1: [val1]

The modification to the slice in the function affects the value of the actual parameter. Does this mean that this is pass-by-reference?

In fact, not really. To answer this question, we must first find out whether the calling function slice m1 has changed. First we need to understand the nature of slicing.

A slice is a description of an array fragment. It contains a pointer to the array, the length of the fragment.

In other words, what we print above is not the slice itself, but the array pointed to by the slice. For another example, verify whether the slice has changed.


  package main
import (
  "fmt"
)
func main() {
  m1 := make([]string, 1)
  m1[0] = "test"
  fmt.Println("调用 func1 前 m1 值:", m1, cap(m1))
  func1(m1)
  fmt.Println("调用 func1 后 m1 值:", m1, cap(m1))
}
func func1 (a []string) {
  a = append(a, "val1")
  fmt.Println("func1中:", a, cap(a))
}
Copy after login
The output results are as follows:

The value of m1 before calling func1: [test] 1

In func1: [test val1] 2

The value of m1 after calling func1: [test] 1

This result shows that the slices have not changed before and after the call. The so-called "change" in the previous example is actually that the elements of the array pointed to by the pointer to the array in the slice have changed. This sentence may be a bit awkward, but it is actually true. Proving once again that parameter passing of reference types is not pass-by-reference.

I want to have a thorough understanding. A slice is a description of an array fragment. It contains the pointer to the array and the length of the fragment. If you are interested, you can read this article: http://www.jb51.net/kf/201604/499045.html. Learn about the memory model of slicing.

Summary

The summary is very simple, and language also needs to see through the phenomenon to see the essence. There is also the conclusion of this article that needs to be remembered:

There is no pass-by-reference in Go.

The above is the detailed content of Go language comparison C++ reference parameter passing. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

In-depth comparison: Vivox100 or Vivox100Pro, which one is more worth buying? In-depth comparison: Vivox100 or Vivox100Pro, which one is more worth buying? Mar 22, 2024 pm 02:06 PM

In today's smartphone market, consumers are faced with more and more choices. With the continuous development of technology, mobile phone manufacturers have launched more and more models and styles, among which Vivox100 and Vivox100Pro are undoubtedly two products that have attracted much attention. Both mobile phones come from the well-known brand Vivox, but they have certain differences in functions, performance and price. So when facing these two mobile phones, which one is more worth buying? There are obvious differences in appearance design between Vivox100 and Vivox100Pro

3 Ways to Change Language on iPhone 3 Ways to Change Language on iPhone Feb 02, 2024 pm 04:12 PM

It's no secret that the iPhone is one of the most user-friendly electronic gadgets, and one of the reasons why is that it can be easily personalized to your liking. In Personalization, you can change the language to a different language than the one you selected when setting up your iPhone. If you're familiar with multiple languages, or your iPhone's language setting is wrong, you can change it as we explain below. How to Change the Language of iPhone [3 Methods] iOS allows users to freely switch the preferred language on iPhone to adapt to different needs. You can change the language of interaction with Siri to facilitate communication with the voice assistant. At the same time, when using the local keyboard, you can easily switch between multiple languages ​​to improve input efficiency.

Which one has more potential, SOL coin or BCH coin? What is the difference between SOL coin and BCH coin? Which one has more potential, SOL coin or BCH coin? What is the difference between SOL coin and BCH coin? Apr 25, 2024 am 09:07 AM

Currently, the potential coins that are favored by the currency circle include SOL coin and BCH coin. SOL is the native token of the Solana blockchain platform. BCH is the token of the BitcoinCash project, which is a fork currency of Bitcoin. Because they have different technical characteristics, application scenarios and development directions, it is difficult for investors to make a choice between the two. I want to analyze which one has more potential, SOL currency or BCH? Invest again. However, the comparison of currencies requires a comprehensive analysis based on the market, development prospects, project strength, etc. Next, the editor will tell you in detail. Which one has more potential, SOL coin or BCH? In comparison, SOL coin has more potential. Determining which one has more potential, SOL coin or BCH, is a complicated issue because it depends on many factors.

Windows 10 vs. Windows 11 performance comparison: Which one is better? Windows 10 vs. Windows 11 performance comparison: Which one is better? Mar 28, 2024 am 09:00 AM

Windows 10 vs. Windows 11 performance comparison: Which one is better? With the continuous development and advancement of technology, operating systems are constantly updated and upgraded. As one of the world's largest operating system developers, Microsoft's Windows series of operating systems have always attracted much attention from users. In 2021, Microsoft released the Windows 11 operating system, which triggered widespread discussion and attention. So, what is the difference in performance between Windows 10 and Windows 11? Which

Comparison of Huawei, ZTE, Tmall, and Xiaomi TV boxes Comparison of Huawei, ZTE, Tmall, and Xiaomi TV boxes Feb 02, 2024 pm 04:42 PM

TV boxes, as an important device that connects the Internet and TV, have become more and more popular in recent years. With the popularity of smart TVs, consumers are increasingly favoring TV box brands such as Tmall, Xiaomi, ZTE and Huawei. In order to help readers choose the TV box that best suits them, this article will provide an in-depth comparison of the features and advantages of these four TV boxes. 1. Huawei TV Box: The smart audio-visual experience is excellent and can provide a smooth viewing experience. Huawei TV Box has a powerful processor and high-definition picture quality. Such as online video, and built-in rich applications, music and games, etc., it supports a variety of audio and video formats. Huawei TV box also has voice control function, which makes operation more convenient. You can easily cast the content on your mobile phone to the TV screen. Its one-click casting

Comparative evaluation of Vivox100 and Vivox100Pro: Which one do you prefer? Comparative evaluation of Vivox100 and Vivox100Pro: Which one do you prefer? Mar 22, 2024 pm 02:33 PM

Comparative evaluation of Vivox100 and Vivox100Pro: Which one do you prefer? As smartphones continue to become more popular and more powerful, people's demand for mobile phone accessories is also growing. As an indispensable part of mobile phone accessories, headphones play an important role in people's daily life and work. Among many headphone brands, Vivox100 and Vivox100Pro are two products that have attracted much attention. Today, we will conduct a detailed comparative evaluation of these two headphones to see their advantages and disadvantages

Performance comparison and advantages and disadvantages of Go language and other programming languages Performance comparison and advantages and disadvantages of Go language and other programming languages Mar 07, 2024 pm 12:54 PM

Title: Performance comparison, advantages and disadvantages of Go language and other programming languages. With the continuous development of computer technology, the choice of programming language is becoming more and more critical, among which performance is an important consideration. This article will take the Go language as an example to compare its performance with other common programming languages ​​and analyze their respective advantages and disadvantages. 1. Overview of Go language Go language is an open source programming language developed by Google. It has the characteristics of fast compilation, efficient concurrency, conciseness and easy readability. It is suitable for the development of network services, distributed systems, cloud computing and other fields. Go

How to set the language of Win10 computer to Chinese? How to set the language of Win10 computer to Chinese? Jan 05, 2024 pm 06:51 PM

Sometimes we just install the computer system and find that the system is in English. In this case, we need to change the computer language to Chinese. So how to change the computer language to Chinese in the win10 system? Now Give you specific operation methods. How to change the computer language in win10 to Chinese 1. Turn on the computer and click the start button in the lower left corner. 2. Click the settings option on the left. 3. Select "Time and Language" on the page that opens. 4. After opening, click "Language" on the left. 5. Here you can set the computer language you want.

See all articles