在golang中C++的using some_namespace::object
是什麼?什麼是C++在golang中的「使用」相當於
按照問題here 我可以using namespace common
下面的語句:
import (
. "common"
)
但這將導入整個命名空間。現在我只想使用,比如platform
的定義,類似using common::platform
在Go中是否有與此等效的內容,這樣我就不必一直鍵入common.platform
?
在golang中C++的using some_namespace::object
是什麼?什麼是C++在golang中的「使用」相當於
按照問題here 我可以using namespace common
下面的語句:
import (
. "common"
)
但這將導入整個命名空間。現在我只想使用,比如platform
的定義,類似using common::platform
在Go中是否有與此等效的內容,這樣我就不必一直鍵入common.platform
?
以下代碼在可讀性方面很接近,但效率較低,因爲編譯器無法再內聯函數調用。
import (
"fmt"
"strings"
)
var (
Sprintf = fmt.Sprintf
HasPrefix = strings.HasPrefix
)
而且,它具有fmt
和strings
導入命名到本文件範圍內,這恐怕是C++的using
沒有做的副作用。
Go目前沒有此功能。
這並不是說它永遠不會被添加:該語言有open proposal to add "Alias declarations"。
正如其他人所說,在Go中是不可能的。在Go中,您導入包,而不是來自包的函數或類型。
請注意,如果您創建幫手包,您可以輕鬆實現您想要的操作。
假設您只想使用fmt.Println()
和fmt.Printf()
函數。創建一個幫助包:
package helper
import "fmt"
func Println(a ...interface{}) (n int, err error) {
return fmt.Println(a...)
}
func Printf(format string, a ...interface{}) (n int, err error) {
return fmt.Printf(format, a...)
}
以及您想要的C++的‘使用’功能,使用點.
進口:
import . "helper"
func Something() {
Println("Hi")
Printf("Using format string: %d", 3)
}
的結果是,只有helper
包的出口標識會在範圍內,沒有別的從fmt
包。當然,您也可以使用這個單獨的包helper
來使功能從fmt
以外的包中獲得。 helper
可以導入任何其他包,並有一個「代理」或委託人功能發佈其功能。
就我個人而言,我並不覺得需要這個。我只會輸入fmt
並使用fmt.Println()
和fmt.Printf()
來調用它的功能。
也許你可以重命名包:
import ( c "common" cout2 "github.com/one/cout" cout2 "github.com/two/cout" )
那麼只需要鍵入c.Platform
@juanchopanza我敢肯定的是OP尋找像'使用std :: cout;'然後就可以使用'cout'而不是'std :: cout'。 – NathanOliver
@NathanOliver這就是我正在尋找的。 – cookieisaac
如果軟件包的命名和輸出內容的命名匹配得當,則不需要多餘的額外輸入,但是有很多額外的可讀性。 – Volker